-w比较会判断你对文件是否有可写权限。脚本test16.sh只是脚本test13.sh的修改版。现在不单检查item_name是否存在、是否为文件,还会检查该文件是否有写入权限。
$ cat test16.sh
#!/bin/bash
# Check if a file is writable.
#
item_name=$HOME/sentinel
echo
echo "The item being checked: $item_name"
echo
[...]
echo "Yes, $item_name is a file."
echo "But is it writable?"
echo
#
if [ -w $item_name ]
then #Item is writable
echo "Writing current time to $item_name"
date +%H%M >> $item_name
#
else #Item is not writable
echo "Unable to write to $item_name"
fi
#
else #Item is not a file
echo "No, $item_name is not a file."
fi
[...]
$
$ ls -l sentinel
-rw-rw-r--. 1 Christine Christine 0 Jun 27 05:38 sentinel
$
$ ./test16.sh
The item being checked: /home/Christine/sentinel
The item, /home/Christine/sentinel, does exist.
But is it a file?
Yes, /home/Christine/sentinel is a file.
But is it writable?
Writing current time to /home/Christine/sentinel
$
$ cat sentinel
0543
$
变量item_name被设置成$HOME/sentinel,该文件允许用户进行写入。因此当脚本运行时,-w测试表达式会返回非零退出状态,然后执行then代码块,将时间戳写入文件sentinel中。
如果使用chmod关闭文件sentinel的用户 写入权限,-w测试表达式会返回非零的退出状态码,时间戳不会被写入文件。
$ chmod u-w sentinel
$
$ ls -l sentinel
-r--rw-r--. 1 Christine Christine 5 Jun 27 05:43 sentinel
$
$ ./test16.sh
The item being checked: /home/Christine/sentinel
The item, /home/Christine/sentinel, does exist.
But is it a file?
Yes, /home/Christine/sentinel is a file.
But is it writable?
Unable to write to /home/Christine/sentinel
$
chmod命令可用来为读者再次回授写入权限。这会使得写入测试表达式返回退出状态码0,并允许一次针对文件的写入尝试。