1

This is so simple yet...

FOLDER='/home/user/.ssh'
SSH="$FOLDER/local-rsync-key.pub"
if [ -f "$SSH" ]; then
...

It looks that Bash considers the '-' as a minus signal and the IF statement always fails... How can I write this variable the right way?

UPDATE: This is another real example:

I am tring to rename files with "-" in front of the filename, for example: "-0001.jpg"

However, everyime I try to run:

for i in *; do mv "$i" "${i//-/}"; done

or:

for i in *; do mv "$i" "${i#*-}"; done

I got this error:

mv: invalid option -- '0'
Try `mv --help' for more information.

Thanks for any light!

Roger
  • 8,286
  • 17
  • 59
  • 77
  • It seems to be a duplicate of [this](http://stackoverflow.com/questions/6557985/mv-invalid-option-0) quetion. – Lynch Jul 02 '11 at 16:59

3 Answers3

3

You should not have a $ in front of your SSH assignment, that's only needed when you're using the variable. Without that, it works fine, as in the following transcript:

pax> touch abc-xyz

pax> ll a*
-rw-r--r-- 1 pax paxgrp 0 2011-06-24 05:15 abc-xyz

pax> FOLDER=.

pax> $SSH="$FOLDER/abc-xyz"
bash: =./abc-xyz: No such file or directory

pax> SSH="$FOLDER/abc-xyz"

pax> if [ -f "$SSH" ]
...> then
...>     echo yes
...> fi
yes

pax> _
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3

The answer is to use "--" (indicating no more options) after "mv" or "./" before the name of the file (indicating it is about a file). For example:

for i in *; do mv -- "$i" "${i#*-}"; done

or:

for i in *; do mv -- "$i" "./${i#*-}"; done
Roger
  • 8,286
  • 17
  • 59
  • 77
  • It's worth noting that this works for pretty much any Linux tool ever. `find` is one notable exception. – l0b0 Jul 05 '11 at 14:27
1

In bash syntax, when you set a variable just use the variable name:

VAR=value

When you reference the variable, use the $ prefix:

echo $VAR

Your code has a stray dollar sign prefix where you are trying to set the SSH variable. The dashes inside the variable should be no problem.

Caleb
  • 5,084
  • 1
  • 46
  • 65