您的位置:首页 > 运维架构 > Shell

shell输入,输出

2018-04-03 22:14 246 查看
处理用户 输入

echo $(basename $0)#若 不加 basename的话,若运行脚本时输入的绝对路径,输出的脚本名 也是绝对路径
echo $1
echo $2
echo $#
#./1.sh 脚本名
#hello
#world
#2参数个数


移位shift,左移一位,$0不变

echo
while [ -n "$1" ]#注意一定要有双引号,不然$1一直左移为空,会无限输出;而且-n为字符串判定方式
do
case "$1" in
-a)
echo "found -a";;
-b)
echo "found -b";;
*)
echo "found none";;
esac
shift
done


获取用户输入read

read -p "Enter your name: " first last
echo "Checking data for $last, $first..."
$
$ ./test23.sh
Enter your name: Rich Blum
Checking data for Blum, Rich...
$
也可以在 read 命令行中不指定变量。如果是这样, read 命令会将它收到的任何数据都放进
特殊环境变量 REPLY 中。
$ cat test24.sh
#!/bin/bash
# Testing the REPLY Environment variable
#
read -p "Enter your name: "
echo
echo Hello $REPLY, welcome to my program.
#
$
$ ./test24.sh
Enter your name: Christine
Hello Christine, welcome to my program.
$
REPLY 环境变量会保存输入的所有数据,可以在shell脚本中像其他变量一样使用。

read -t 5 计时器 ,超过时间返回非零状态码
read -s 隐藏读取


一个文件最多打开9个标准文件描述符

0 STDIN
1 STDOUT
2 STDERR


ls -al test test2 test3 badtest 2> test6 1> test7

ls -al test test2 test3 badtest &> test7
#将 STDERR 和 STDOUT 的输出重定向到同一个输出文件


临时 重定向:在 某一条命令后进行 重定向

ls -al badfile >&2
echo "hello,world"

./1.sh 2>1.txt


永久 重定向:其实就是声明全部都重定向

exec 2>file#执行脚本时就不需要指定文件了


重定向输入:

exec 0< testfile


重定向文件描述符:

exec 3>&1
exec 1>file


关闭文件描述符:

exec 3>&-


将输出导入到/dev/null,就可以把输出丢弃从而不输出了

ls -al > /dev/null


清除文件的一个方法:

cat /dev/null > testfile


创建临时文件、目录

mktemp  filename.XXXXXX
mktemp -t filename.XXXXXX #强制在/tmp目录下创建
mktemp -d dirname.XXXXXX#创建目录


文件

tee命令 :将 STDIN的数据同时重定向到STDOUT和

tee filename#默认覆盖文件,若要追加,使用-a
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell