Bash party

Bash 헷갈릴 때 보는 포스트

Variable Assignment

띄어쓰기 없이 변수명=값. 환경변수와는 별개.

foo=bar # OK
echo $foo # output: bar

foo =bar # WRONG; arg0: "foo", arg1: "=bar"
foo = bar # WRONG; arg0: "foo", arg1: "=", arg2: "bar"
foo= bar # WRONG; executes "bar" with empty envvar "foo"

Double Quotes vs. Single Quote

작은 따옴표는 literal string, 큰따옴표는 치환 실행함

foo=bar
echo "$foo" # output: bar
echo '$foo' # output: $foo

Bash special chars

https://tldp.org/LDP/abs/html/special-chars.html

Substitution

# Command substitution
# Execute command, and substitute $() with the output
$(command)

# Process substitution
# Execute command, place the output in a temporary file (such as /dev/fd/42), and substitute <() with the output
<(command)

# Example
# Compare foo and bar directory
diff <(ls foo) <(ls bar)

Conditions

Use “test”/”[” or “[[“. Try “man [“.

Compound Statements

https://www.gnu.org/software/bash/manual/html_node/Compound-Commands.html

# Note that wherever a ‘;’ appears in the description of a command’s syntax, it may be replaced with one or more newlines.

# for loop
for name [ [in [words …] ] ; ] do commands; done

# Example
for file in "$@"; do
grep foobar "$file"
done

Shell globbing

# {} expansion
convert image.{png,jpg}
# is equal to
convert image.png image.jpg

Leave a comment

Your email address will not be published. Required fields are marked *