关于linux:Linux-Shell-变量

4次阅读

共计 1056 个字符,预计需要花费 3 分钟才能阅读完成。

定义变量

# 等号的四周不能有空格
url=http://www.qq.com/shell/

name='我的网站'

author="wu"

应用变量

# 举荐给所有变量加上花括号 {}
echo $author
echo ${author}
echo "I am good at ${skill}Script"
# 倡议应用引号突围,防止出现格局凌乱的状况
LSL=`ls -l`
echo "${LSL}"

批改变量的值

url="http://www.qq.com"
url="http://www.qq.com/shell/"

单引号和双引号的区别

#!/bin/bash
url="http://www.qq.com"
website1='我的网站:${url}'
website2="我的网站:${url}"

# 我的网站:${url}
echo $website1

# 我的网站:http://www.qq.com
echo $website2

将命令的后果赋值给变量

格局:

variable=`command`
variable=$(command)
log=$(cat log.txt)
echo $log
#!/bin/bash

begin_time=`date`    #开始工夫,应用 `` 替换
sleep 20s
finish_time=$(date)  #完结工夫,应用 $() 替换

echo "Begin time: $begin_time"
echo "Finish time: $finish_time"
#!/bin/bash
begin_time=`date +%s`    #开始工夫,应用 `` 替换
sleep 20s
finish_time=$(date +%s)  #完结工夫,应用 $() 替换
run_time=$((finish_time - begin_time))  #时间差

echo "begin time: $begin_time"
echo "finish time: $finish_time"
echo "run time: ${run_time}s"
# 应用 $() 反对嵌套,反引号不反对
Fir_File_Lines=$(wc -l $(ls | sed -n '1p'))
echo "$Fir_File_Lines"

要留神的是,$() 仅在 Bash Shell 中无效,而反引号可在多种 Shell 中应用。所以这两种命令替换的形式各有特点,到底选用哪种形式全看集体需要。

删除变量

#!/bin/sh
myUrl="http://www.qq.com/shell/"
unset myUrl
echo $myUrl

参考:http://c.biancheng.net/view/1…

正文完
 0