简体   繁体   中英

Parameter expansion

I am trying the following code in shell for Parameter Expansion

#!/bin/sh
count
echo ${count:-60}
echo ${count:=120}
echo $count
echo ${count:+80}
x = 'The host name is google'
echo ${#x}

Output

./test_varexp.sh: line 2: count: command not found
60
120
120
80
./test_varexp.sh: line 7: x: command not found
0

With the above code and output in context i have following questions;

  1. The parameter expansion with '=' symbol should set the value of count to 120, which is also seen as happening when we printed the value of count , but in the next line it is getting overwritten when i use the same with "+" which should only check for existence. Can somebody explain this anomaly? or Can somebody explain if count is actually existing or not?

  2. The parameter expansion for ${#x} is not at all working. Can someone tell me if there is any syntax error?

I am trying the above code

[root@dtltrhel5u8 shellscripts]# uname -a
Linux dtltrhel5u8 2.6.18-308.el5 #1 SMP Fri Jan 27 17:17:51 EST 2012 x86_64 x86_64 x86_64 GNU/Linux

You are confusing a number of issues here. The shell will tokenize your input on whitespace (or generally on IFS , but respecting any quoting) and look for assignments and commands, in that order. If the first token contains = then it is an assignment, which may be followed by further assignments or a command. If not, then it's a command, and any remaining parameters are command arguments. (There used to be a time when assignments could also follow a command, and there are ways to make modern shells behave like that, for backwards compatibility; but let's just ignore that sidetrack.)

So count is a command, which obviously doesn't exist. Perhaps you meant count= to define the variable without a value (this is distinct from leaving it unset).

The expansion ${count:+80} produces the value 80 if the variable is set and nonempty; this is precisely what you are getting. If the variable were empty or unset, an empty string would be substituted instead.

If you wanted to assign a value to x , again, the equals sign and the value needs to be part of the first token; so

x='The host name is google'

Once the assignment works, the string's length will no longer be zero.

Your first question is easily explained by the documentation http://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

Specifically, ${count:+80} returns nothing if count is unset, and 80 if it is set. The value of count is still 120.

Your other syntax error is that you shouldn't put spaces around the = .

x='The host name is google'
echo ${#x}

prints 23 .

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