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.

2
  • 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. Commented Jul 1, 2016 at 19:34
  • @John I've further edited the original question as to avoid duplicating the previously asked question unix.stackexchange.com/questions/131766/… Commented Jul 1, 2016 at 20:11

1 Answer 1

3

Use quotes:

shasum -a "$sha" "$shapath"

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

6
  • 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 Commented Jul 1, 2016 at 17:56
  • 1
    @andrewkeithly Use command substitution then foobar=$(shasum -a "$sha" "$shapath") Commented Jul 1, 2016 at 18:00
  • I've tried this, it doesn't work. If I echo foobar it gives me shasum: ~/../checksum.dmg: Commented Jul 1, 2016 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/.... Commented Jul 1, 2016 at 19:13
  • Thanks for the suggestion @heemayl. Unfortunately, using the full path still gave me shasum: /.../checksum.dmg upon using echo Commented Jul 1, 2016 at 19:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.