8

I see some bash scripts use $1, $2, … to access arguments passed on the command line, and some scripts use ${1}, ${2}, …. What's the difference between these two syntaxes?

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
Vlad
  • 9,180
  • 5
  • 48
  • 67
  • 4
    adding `{}` makes it clear what you're doing. it's the difference between `echo $12` and `echo ${1}2`. first one is accessing the 12th argument to the script, which the other one is the first argument, with a literal `2` appended. – Marc B Dec 15 '15 at 19:09
  • 2
    There is none. However, when you use brackets around the variable's names, you explicitly state the name of the variable to be accessed. This makes a difference when accessing arrays or positional parameters larger than 10 : `$10` won't work, but `${10}` will. With arrays, `$x[5]` won't work, but `${x[5]}` will. – Daniel Kamil Kozar Dec 15 '15 at 19:10
  • 1
    And it's not just args, it's any environment variable. – Don Branson Dec 15 '15 at 19:10
  • 2
    @DonBranson, any *shell* variables. All environment variables (with valid names) are shell variables, but not all shell variables are environment variables. – Charles Duffy Dec 15 '15 at 19:17
  • @Charles you are correct! I misspoke. – Don Branson Dec 15 '15 at 19:19
  • 4
    @MarcB Wrong. `$12` is equivalent to `${1}2`. You can only leave out the braces when your index is a single digit. – 4ae1e1 Dec 15 '15 at 19:24

0 Answers0