|
|
[one-liner]: Special Variables in Bash
slmingol posted this in tips & tricks on June 19th, 2009, @ 7:14 pm
These are blatantly ripped off from a Dave Taylor article that I recently read in the May 2009 edition of linuxjournal but I’m capturing them here in a blog post because I can never seem to remember them. I’ve also mixed in a few of my own for good measure.
Variable Basics
1
2
3
4
5
6
7
8
9
10
11
12
| # bare variable
% var1="I like pizza"
% echo $var1
I like pizza
# protected variable
% echo ${var1}
I like pizza
# protected variable with appended text
% echo "${var1}, steve"
I like pizza, steve |
Variable Value’s Length
1
2
3
4
| # length of variable's value
% test="the rain in Spain"
% echo ${#test}
17 |
Variable Patterns & Substitutions
1
2
3
4
5
6
7
8
| # pattern match by variable names
% echo ${!t*}
test
% thimble="full"
% tart="pop"
% echo ${!t*}
tart test thimble |
1
2
3
4
5
6
7
8
9
10
| # variable substitution
#--> (similar to s/old pat/new pat/)
% test="The Rain in Spain"
% echo ${test/ain/ixn}
The Rixn in Spain
# variable substitution globally!
#--> (similar to s/old pat/new pat/g)
% echo ${test//ain/ixn}
The Rixn in Spixn |
1
2
3
4
5
6
7
8
9
| # variable substitution with anchoring to the beginning
#--> (similar to s/^old pat/new pat/)
% echo ${test/#ain/ixn}
The Rain in Spain
# variable substitution with anchoring to the end
#--> (similar to s/old pat$/new pat/)
% echo ${test/%ain/ixn}
The Rain in Spixn |
1
2
3
4
5
| # example of substitution in action
#--> (replacing a file's .txt extension with the PID)
% test="The Rain in Spain.txt"
% echo ${test/%.*/}.$$
The Rain in Spain.23001 |
Command Substitutions
1
2
3
4
5
| # command substitution #1 (the slacker/hacker way)
% echo the date is `date`
# command substitution #2 (the preferred way)
% echo the date is $(date) |
1
2
3
4
5
| # catting a file #1 (verbose)
% $(cat file)
# catting a file #2 (leet way)
% $(< file) |
Quoting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| # bare w/o quotes
% echo the date is $(date)
the date is Fri Jun 9 21:32:01 EDT 2009
# with double quotes
% echo the date is "$(date)"
the date is Fri Jun 9 21:31:03 EDT 2009
# with single quotes
% echo the date is '$(date)'
the date is $(date)
# with escaped double quotes
% echo the '$HOSTNAME' is \"$HOSTNAME\"
the $HOSTNAME is "mulder"
# with escaped single quotes
% echo the '$HOSTNAME' is \'$HOSTNAME\'
the $HOSTNAME is 'mulder' |
NOTE: For further details regarding my one-liner blog posts, check out my one-liner style guide primer.
|
This is really good stuff. Thanks for posting it.