-1

Consider the script print_folder.sh:

echo $1
ls -F $1

This simple script expects a user to supply the name of a folder through the first argument. The script will first print out the name of the folder and then it's contents.

Now, let's consider two cases of $1: the one when $1 doesn't and the one when $1 does contain spaces.


Case 1: No Spaces
[nikola@leviathan ~]$ ./print_folder.sh Pictures/
Pictures/
Gifs/  Miscellaneous/  Screenshots/  Wallpapers/

No problems, everything works fine.

Case 2: Spaces

[nikola@leviathan ~]$ ./print_folder.sh Templates/URxvt\ Colorschemes/
Templates/URxvt Colorschemes/
ls: cannot access 'Templates/URxvt': No such file or directory
ls: cannot access 'Colorschemes/': No such file or directory

See, here is the problem. The cause of it is obviously that $1 has the value of Templates/URxvt Colorschemes instead of Templates/URxvt\ Colorschemes.


How can I make $1 contains the backslashes that signify special characters instead of removing them? Also, keep in mind that I will not accept workarounds like making ls read spaces "normally" (i.e. is read as a space in a folder's name instead of another folder's name) since I don't use $1 as an argument only to ls so that may be not possible with other commands.
Hanlon
  • 432
  • 4
  • 13
  • 1
    Use double-quotes around the argument. – nneonneo Aug 15 '18 at 08:04
  • Possible duplicate of [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/q/131766/56041), [Bash variables with spaces](https://stackoverflow.com/q/5819423/608639), [When to wrap quotes around a shell variable?](https://stackoverflow.com/q/10067266/608639), [How do I pass on script arguments that contain quotes/spaces?](https://stackoverflow.com/q/5720194/608639), etc. – jww Aug 15 '18 at 08:30

1 Answers1

0

The better, safer and simpler way of having ls (or any command) parse your variable as a single argument rather than two would be to instead of inserting backlashes into the variable surround your surround it with quotes when using it: ls -F "$1".

gaderian
  • 1
  • 1
  • The question has been asked and answered many times before. In this instance I think it is better to find a mature duplicate rather than restating something that has been stated many times before. – jww Aug 15 '18 at 11:50
  • Right, should have thought of that. Will keep it in mind in the future :) – gaderian Aug 15 '18 at 14:04