Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Study: Bash Variable Quoting
- Bash is designed to automatically reinterpret where strings end and begin based on whitespace unless the string is
- surrounded by double quotes. It's because Bash is so string-centric that you can call a script or function like this:
- ```bash
- some_func John Doe "age 24"
- ```
- and all of those argument will be interpreted as string literal, not variable name or command names. If you omit the
- quotes around "age 24" the arg count will increase to four.
- Inside the function you have a similar situation. Even if the last arg is passed in with double quotes you can run into
- this:
- ```bash
- printf $1 #-> John
- printf $2 #-> Doe
- printf $3 #-> Age
- ```
- This is called __word splitting__, the `24` is actually still sent to `printf`, but it's send as second (discarded)
- arguments. To put it more accurately, each function/script gets it's arguments as an array list of words where each
- element can only be more than one word if it is wrapped in double quotes.
- __Parameter expansion__ is the procedure to get the value from the referenced entity, like expanding a variable to
- print its value. This is when $3 is expanded into an array, using whitespace as delimitors. You can think
- of double quotes in bash as a shell protecting whatever is inside from parameter expansion.
- Inside of a script or function you have `"$@"`, which holds all the arguments passed in as a list. If we execute:
- ```bash
- some_func John Doe "age 24"
- ```
- `"$@"`, inside the function, basically contains an array which would be declared and used like this:
- ```bash
- array=("John" "Doe" "age 24")
- echo "${array[0]}"
- echo "${array[1]}"
- echo "${array[2]}"
- ```
- The the quotes around "John" and "Doe" aren't really need but they are put there for consistency. The
- space between them I interpreted by `(` and `)` to make a new index, not the `"` symbol. In fact,
- try this `array=("John""Doe""age 24")` and you will get:
- ```bash
- John
- Doeage 24
- ```
- The `"` are discarded by when passed into functions too. You might not believe it, but all of these work:
- ```bash
- dirname /User/Jeff
- dirname "/Us"er"/Jeff"
- ```
- What doesn't work is if you have a path that contains a space and is not surrounded by double quotes.
- ```bash
- dirname "Users/Jeff/a dir/the index.html" # works
- dirname Users/Jeff/a" "dir/the" "index.html # works
- dirname "Users/Jeff/a" "dir/the index.html" # fails
- ```
- As long as the quotes are open when we hit a space, it works. The most bizzare aspect of Bash is that
- `"` is ignored when parsing a script or function name, all of these work:
- ```bash
- echo $(dirn"am"e "/Us"er"/Jeff")
- it_works () { echo "it works"; }
- echo `it_"works"`
- echo $("it_"works)
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement