常用linux shell脚本分享

发布时间:2020-03-04编辑:脚本学堂
分享几个linux shell脚本,包括判断登录用户、判断是否继续执行、隐藏输入、屏蔽显示等shell脚本,感兴趣的朋友参考下。

1、判断登录用户
1.1、脚本
 

复制代码 代码示例:
[devtac@test_1 shell]$ vi check_user.sh
#! /bin/sh
echo "You are logged in as `whoami`";
if [ `whoami` != devtac ]; then
  echo "Must be logged in as devtac to run this script."
  exit
fi
echo "Running script at `date`"

1.2、运行结果
 

复制代码 代码示例:
[devtac@test_1 shell]$ chmod a+x check_user.sh
[devtac@test_1 shell]$ ./check_user.sh
You are logged in as devtac
Running script at 2014年 12月 09日 星期二 13:35:17 CST

2、判断是否继续执行
2.1 脚本
 

复制代码 代码示例:
[devtac@test_1 shell]$ vi do_continue.sh
#! /bin/sh
doContinue=n
echo "Do you really want to continue? (y/n)"
read doContinue
if [ "$doContinue" != y ]; then
   echo "Quitting..."
   exit
fi
echo "OK... we will continue."

2.2 运行结果
 

复制代码 代码示例:
[devtac@test_1 shell]$ ./do_continue.sh
Do you really want to continue? (y/n)
y
OK... we will continue.
[devtac@test_1 shell]$ ./do_continue.sh
Do you really want to continue? (y/n)
n
Quitting...
[devtac@test_1 shell]$

3、隐藏输入
3.1 脚本
 

复制代码 代码示例:

[devtac@test_1 shell]$ vi hide_input.sh
#! /bin/sh
stty -echo
echo -n "Enter the database system password:"
read pw
stty echo

echo "$pw was entered"

3.2 结果
 

复制代码 代码示例:
 ./hide_input.sh
Enter the database system password:123qweasd was entered
[devtac@test_1 shell]$

3.3 解析
stty 命令

3.3.1 man 手册定义
 

复制代码 代码示例:

DESCRIPTION
Print or change terminal characteristics.

[devtac@test_1 shell]$ stty -a
speed 38400 baud; rows 47; columns 125; line = 0;
intr = ^C; quit = ^; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S;
susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts -cdtrdsr
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke

本例中使用的参数:
 

[-]echo
 echo input characters

屏蔽显示:
stty -echo #禁止回显
stty echo #打开回显

测试方法:
 

stty -echo;read;stty echo;read

简述:
使用stty -echo 的效果,就像输入linux 登录密码时效果一样。