Linux shell --变量

1.变量定义

变量定义的=前后不能有空格

variable=value
name=sarath
age=28

2.访问变量

使用$访问变量

echo $variable
echo $name
echo $age

3.设置变量来自用户输入

使用read函数

#!/bin/bash
echo "what is your name?"
read name
echo "Hello $name!. Welcome to Slashroot Scripting Tutorial"

执行以上脚本首先执行“what is your name”、然后等待用户输入。

4.如何把一个命令的输出覆盖变量

把命令直接放到双引号中,就OK了

#!/bin/bash
DATE=`date`
echo "Today is $DATE"

5.如何给shell脚本的变量赋值

0 1,表示第一个变量,$2表示第二个变量。依次类推

#!/bin/bash
firstname=$1
lastname=$2
scriptname=$0
echo "Hello!. So your Firstname is $firstname, and your Lastname is $lastname and the script that you are executing is $scriptname"

或者:

#!/bin/bash
echo "Hello!. So your Firstname is $1, and your Lastname is $2 and the script that you are executing is $0"

脚本执行:

# ./test1.sh Sarath Pillai

6.如何验证一个命令在shell脚本里是执行成功的

每一个命令在shell脚本里执行成功后返回一个0-255的状态数字。0表示执行成功,其他非零表示执行失败。

这些值会存放在 $?

root@localhost:/opt# ls
testdirectory
root@localhost:/opt# echo $?
0
root@localhost:/opt# ls )
-bash: syntax error near unexpected token `)'
ubuntu@ip-10-12-4-160:/opt$ echo $?
2

7.如何清除一个变量的值

使用unset

#!/bin/bash
variable=2
echo The variable value is $variable
unset variable
echo The variable value is $variable

参考

https://www.slashroot.in/variables-linux-shell-scripts-explained-examples

猜你喜欢

转载自blog.csdn.net/ai_xiangjuan/article/details/80616006
今日推荐