[Linux Shell学习系列五]Shell编程基础-Bash的内部变量,位置参数和特殊参数

Posted workingdiary

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Linux Shell学习系列五]Shell编程基础-Bash的内部变量,位置参数和特殊参数相关的知识,希望对你有一定的参考价值。

1. Bash的内部变量

1)$BASH变量:用于引用Bash实例的全路径名;

$ echo $BASH 
/bin/bash

2)$HOME变量:当前用户的HOME目录,通常是/home/<username>;

$ echo $HOME
/home/user1

3)$IFS变量:内部字段分隔符的缩写;

$ set x y z
$ echo "$*"
x y z
$ set IFS=":;-" #可以修改
$ echo "$*"
x:y:z

4)$OSTYPE变量:操作系统的类型;

$ echo $OSTYPE
linux-gnu

5)$SECONDS变量:脚本已经运行的秒数;

$ cat echotime.sh 
#!/bin/bash
#2020-05-18

TIME_LIMIT=5
INTERVAL=1

echo 
echo "Use Ctrl+C to leave before $TIME_LIMIT seconds."
echo 

while [ "$SECONDS" -le "$TIME_LIMIT" ]
do
        sleep $INTERVAL
        echo $(date) >> /home/ntrade/20200511study/time.log
        if [ "$SECONDS" -eq 1 ]
        then
                units=second
        else
                units=seconds
        fi
        echo "This script has been running for $SECONDS $units."
done

$ ./echotime.sh #执行脚本 Use Ctrl+C to leave before 5 seconds. This script has been running for 1 second. This script has been running for 2 seconds. This script has been running for 3 seconds. This script has been running for 4 seconds. This script has been running for 5 seconds. This script has been running for 6 seconds.

6)$TMOUT变量:如果该变量被设置为非0,则Bash将其作为read默认的超时秒数;

$ cat readtimeout.sh 
#!/bin/bash
#2020-05-18

set -o nounset #Treat unset variables as an error.
TMOUT=3

echo "Are you sure? (Y/N)"
read input

if [ "$input" == "Y" ]
then 
        echo "Continue..."
else 
        echo "Exit!"
fi

$ ./readtimeout.sh  #执行脚本
Are you sure? (Y/N) #此时如果一直不输入,则3秒后自动退出
Exit!

7)$UID变量:当前用户的帐号标识码(ID号),/etc/passwd中记录值(只读);输出真实ID,即使通过su获得了其他用户的权限。

$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
... #省略内容
user1:x:1001:1001::/home/user1:/bin/bash

$ echo $UID #使用user1执行
1001

 

2. 

以上是关于[Linux Shell学习系列五]Shell编程基础-Bash的内部变量,位置参数和特殊参数的主要内容,如果未能解决你的问题,请参考以下文章

实验五 shell脚本编程

实验五 shell脚本编程

实验五 shell脚本编程

实验五 shell脚本编程

实验五 shell脚本编程

实验五 shell脚本编程