简体   繁体   中英

What does this expression evaluate to? (bash shell script)

I am trying to do a code walk through a badly written bash script.

I have come across this statement:

FOOBAR_NAME=`date +WeekNo.%W`

There are no prior declarations of any of the RHS variables in the script, lines preceding this statement.

So my question is:

What does FOOBAR_NAME resolve to, when it is used a few lines down in the script as $FOOBAR_NAME ?

Try it!

$date +WeekNo.%W
WeekNo.30

There are no variables being referenced in the RHS.

The backtick operator (`` ) evaluates its contents and returns the output, similar (identical?) to $() . It's a quick way to write an . It's a quick way to write an eval` (in other languages).

Type date +WeekNo.%W in a shell. What is printed (in stdout, with newlines collapsed) is what will be stored in FOOBAR_NAME .

Note that the evaluation occurs only once, which is during the assignment. date isn't executed each time you reference FOOBAR_NAME .

See man date for a description of the date command and it's formatting options. %W is week number.

This is using a format string to the date command to create the a string that contains the week number.

The backticks execute the command between them; and the line assigns the result to the shell variable FOOBAR_NAME.

So if you really want to know what it does, just cut and paste the text between the `` into a shell and execute it.

You can find the answer in man date : If you specify an argument starting with + , then the rest of that argument is taken as a format string. The Weekno. part is taken literally, the %W does:

%W week number of year, with Monday as first day of week (00..53)

The assignment operator (" = ") assigns the value on its right part to a variable on the left part. Here the variable is FOOBAR_NAME .

The right part is a subshell. The backticks ("`` `") create a subshell. The output of that subshell will go to the variable.

The subshell rurns the Unix date command. The manual page for all Unix commands is on the Internet. There a Unix man page for date . Here, %W will be replaced by the number of the week.

So the variable gets the value "WeekNo" plus the number of the week.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM