4

Could you please help, does exist a command in bash to quote input argument?

script ./test.sh:

#!/bin/bash

echo ${1}

./test.sh "It costs $1" This prints It costs, but how to print it as is It costs $1.

Of course it is possible to quote the argument directly in the command: ./test.sh "It costs \$1" and it prints It costs $1. But how to quote it in the script?

UPDATED: It is possible with single quotes ./test.sh 'It costs $1'

3
  • 1
    Exactly as you just did: echo "It costs \${1}", or with single quotes: echo 'It costs ${1}'. Commented Nov 26, 2018 at 3:19
  • 1
    When your script executes, it's already too late. There is nothing your script can do to get the original misquoted $1 Commented Nov 26, 2018 at 3:20
  • Did you mean to print the an argument, or that the cost is a single dollar? \$1 will do the latter. If you run as-is with just ./test.sh you'll get what you're seeing, but try ./test.sh "a buck". For real clarity, read this manual, especially here & here. Commented Nov 26, 2018 at 15:25

2 Answers 2

4

You may update your program like below to print/display all arguments.

#!/bin/bash

echo "$@"

This will print all the arguments passed while running test.sh. $1 is a variable which substituted with empty string while calling your program test.sh. Inside test.sh, first argument you passed in command line becomes $1, second becomes $2 and so forth.

$@ prints all arguments.

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

1 Comment

Indeed, it is useful to do man bash and read everything under EXPANSION heading. There is so much good info there that many people never see.
3

I often use:

printf "'%s' "  "$@"

This is an alternative to echo when you want each argument quoted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.