0

I am trying to read a piece of text as a command line arg and print it out. This is my shell script (script.sh):

#!/bin/sh

input=${1}
echo ${input}

This is how I am calling my script: ./script.sh Af)}R"}$;AF(@}#@]-

Placing the command line argument in single quotes is not an option in this case. I am getting the following error: -bash: syntax error near unexpected token)'`

I am new to shell script. Please help.

7
  • ) is a special character in sh. You can't use it literally, it needs single quotes or a backslash. Commented Mar 31, 2020 at 11:33
  • You also need to quote the variable: echo "$input" -- using braces is not the same as using quotes. Commented Mar 31, 2020 at 13:16
  • ; will be interpreted as the end of your command if it isn't escaped. Why is placing the argument in single quotes not an option? Commented Mar 31, 2020 at 13:34
  • @BenjaminW. Actually, I am trying to read in some text as part of a bigger program and I can't ask the end user to enter strings in '' Commented Mar 31, 2020 at 13:42
  • Is the user entering the string on the command line, or are you feeding it to your script programmatically? I feel like something's missing. Commented Mar 31, 2020 at 15:24

1 Answer 1

0

You need quotes both in the invocation and in the script's code, as otherwise many of your punctuation characters will be interpreted by either the command-line shell or the script's interpreting shell. Therefore, you'd want this code:

#!/bin/sh

input="${1}"
echo "${input}"

and to invoke as ./script.sh 'Af)}R"}$;AF(@}#@]-' or, by escaping rather than quoting, as ./script.sh Af\)\}R\"\}\$\;AF\(@\}\#@]-


However, in the comments to this question, you noted

I am trying to read in some text as part of a bigger program and I can't ask the end user to enter strings in ''

Presumably, if the end user can't be asked to quote, they also cannot be asked to escape. In this case, you probably don't want this on the command line. Instead, consider using standard input:

#!/bin/sh

IFS= read -r input
echo "${input}"

and invoke as either ./script.sh (after which you type in that code and hit Enter) or as /path/to/other/program |./script.sh (if that other program issues the code on standard output). You can test this by quoting the code to echo: echo 'Af)}R"}$;AF(@}#@]-' |./script.sh

(I assume this makes sense in a non-simplified version of your code. As it stands here, it doesn't do anything, just taking the input from the first command's standard output and then reporting it right back to standard output.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.