Reputation: 1290
Is it valid to use a backticked command:
`command`
inside of $(())
?
For example, like this:
d=$((`date +%s`+240))
I tried this in a shell script and from the prompt, and it works:
#!/bin/sh -u
# get the date in seconds with offset
d=$((`date +%s`+240))
echo "d=\"${d}\""
echo "date:%s=\"`date +%s`\""
But, if I check it at http://www.shellcheck.net/, I get this error:
1 #!/bin/sh -u
2
3 # get the date in seconds with offset
4 d=$((`date +%s`+240))
^––SC1073 Couldn't parse this $((..)) expression.
^––SC1009 The mentioned parser error was in this $((..)) expression.
^––SC1072 Unexpected "`". Fix any mentioned problems and try again.
5 echo "d=\"${d}\""
My bash version is:
[~] # bash --version
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
And, to be clear, on my system, sh
actually runs bash
:
[~] # ls -l /bin/sh; which bash
lrwxrwxrwx 1 root root 4 Jul 18 2013 /bin/sh -> bash
/bin/bash
I submitted feedback about this at http://www.shellcheck.net/, but I haven't heard back from them yet.
Upvotes: 1
Views: 261
Reputation: 551
While $(( 1 + 1 ))
is allowed in POSIX (e.g. http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html and section 2.6.4), some shells might not support it.
The classic way to do $(( $(date +%s)+240 ))
is like this:
d=$( expr $( date +%s) + 240 )
Here, we use expr
, which has been around longer than $((
.
Note that, as per other answers, I have replaced the backtick with $(
since, unlike the backtick, it can nest, like it does above.
Upvotes: 1
Reputation: 241701
According to man bash
, inside an arithmetic substitution ($((expression))
): (emphasis added)
The expression is treated as if it were within double quotes, but a double quote inside the parentheses is not treated specially. All tokens in the expression undergo parameter expansion, string expansion, command substitution, and quote removal.
So as far as bash is concerned, it is legal, since backticks are a form of command substitution. But the $(...)
form of command substitution is preferred.
Upvotes: 1
Reputation: 10653
Yes, it is perfectly valid. But it is not recommended to use backticks at all. You can use $()
instead.
Upvotes: 3