1

I just started learning Bash Script.

My script is accepting 1 to n number of arguments. Each argument is pass to a function rename. My problem is that the argument I pass does not accept space.

script.sh

#!/bin/bash
for FILE in $@
do
    echo "$FILE"
    rename $FILE
done

For Ex:

./script.sh /Users/xyz/Section 5/abc/ /Users/xyz/pqr/ /Users/z/abc

The above argument "/Users/xyz/Section 5/abc/" should be one even if it contains space. But the code in script.sh will break it into two argument.

So the output is:

/Users/xyz/Section
5/abc/
/Users/xyz/pqr/
/Users/z/abc

But My Expected Output should be:

/Users/xyz/Section 5/abc/
/Users/xyz/pqr/
/Users/z/abc

Note: Different solution I tried till now:

1) "/Users/xyz/Section 5/abc/" --> Same output ie 2 different argument

2) '/Users/xyz/Section 5/abc/' --> Same output ie 2 different argument

3) /Users/xyz/Section\ 5/abc/ --> Same output ie 2 different argument

sandy
  • 29
  • 5
  • The problem is that the default field separator is a space, so when you call anything from bash, it will separate the elements by spaces. To avoid that, you can use quotation marks around each element, for example, "/Users/xyz/Section 5/abc/" – CharlieH Feb 06 '18 at 21:14
  • In addition to quoting arguments, `for FILE in $@` needs to be replaced with `for FILE in "$@"`. – John1024 Feb 06 '18 at 21:16
  • 1
    If you've just started, you might find [shellcheck](https://www.shellcheck.net/) useful. It automatically points out the quoting problems in your snippet. – that other guy Feb 06 '18 at 21:16
  • 1
    I don't know how I missed it. Changing $@ to "$@" worked for me. I don't know how. Wasted an hr for this small solution. Thank you – sandy Feb 06 '18 at 21:18
  • @thatotherguy shellcheck is excellent. Thanks for suggesting it. Can you suggest any IDE also? I am writing script in Sublime without any add ons. – sandy Feb 06 '18 at 21:26
  • @sandy Sublime is as good a choice as any, and there's [SublimeLinter-shellcheck](https://github.com/SublimeLinter/SublimeLinter-shellcheck) to show shellcheck suggestions straight in the editor – that other guy Feb 06 '18 at 22:14

0 Answers0