0

I'm writing a simple script that prompts the user for information and saves it as a variable to be passed as arguments in another command. One of the variables stores a path which may include a space. Using the read command's -r tag, the path is retrieved as 'raw' input, ignoring the backslash escape character.

For example:

read -p "Enter checksum algorithm number (1, 224, 256, 384, 512, 512224, 412256): " -a shaa
read -p "Enter a file path: " -re shapath

The problem is I cannot figure out how to run the command with those arguments without it reading the escape character. Solved per @heemayl

I then need to store the output or return value of the command as another variable.

For example:

foo=$(shasum -a "$shaa" "$shapath")

However, when I echo $foo I do not get the expected output of shasum -a "$shaa" "$shapath", but instead get shasum: /.../checksum.dmg

I was able to get it to work by using eval and piping it into var as shown below:

eval shasum -a $sha $shapath > val

I've read I should avoid eval at all costs and it does not allow me to continue forward with the script.

  • Per @heemayl's suggestion, I have edited the question to better reflect the big picture question which was previously only evident in the subsequent comments. – andrewkeithly Jul 01 '16 at 19:34
  • @John I've further edited the original question as to avoid duplicating the previously asked question http://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters – andrewkeithly Jul 01 '16 at 20:11

1 Answers1

3

Use quotes:

shasum -a "$sha" "$shapath"

The variables will be expanded as single arguments irrespective of any spaces in the values.

heemayl
  • 56,300
  • I should have included that I need to store the return value of shasum -a "$sha" "$shapath" in another variable. Which is why I have been using eval – andrewkeithly Jul 01 '16 at 17:56
  • 1
    @andrewkeithly Use command substitution then foobar=$(shasum -a "$sha" "$shapath") – heemayl Jul 01 '16 at 18:00
  • I've tried this, it doesn't work. If I echo foobar it gives me shasum: ~/../checksum.dmg: – andrewkeithly Jul 01 '16 at 18:05
  • @andrewkeithly ~ wont be expanded, you will have to use eval in that case or use other tricks..try using full path e.g. /home/foo/.... – heemayl Jul 01 '16 at 19:13
  • Thanks for the suggestion @heemayl. Unfortunately, using the full path still gave me shasum: /.../checksum.dmg upon using echo – andrewkeithly Jul 01 '16 at 19:21
  • @andrewkeithly your question is a bit value, could you please edit your question and add what you actually want at the end and what you have right now? – heemayl Jul 01 '16 at 19:22