得之我幸 失之我命

when someone abandons you,it is him that gets loss because he lost someone who truly loves him but you just lost one who doesn’t love you.

bash -c 的必要性

在看别人写的脚本的时候,会发现类似下面一个写法,然后就会好奇这个写法的必要性

1
$ bash -c "echo test >> test.txt"

现在有这么一个文件 test.txt 它是 root 用户才能读写,需要在脚本中对它进行修改,比如追加一行

1
2
3
4
5
6
$ ls -l test.txt
-rw-r--r-- 1 root root 5 Oct 25 13:45 test.txt
$ echo test >> test.txt # 直接 echo,不行
-bash: test.txt: Permission denied
$ sudo echo test >> test.txt # 加 sudo 提权,行不行?
-bash: test.txt: Permission denied # 不行

第二种方式为什么不行?

因为重定向符号 “>” 和 “>>” 也是 bash 的命令,使用 sudo 只是让 echo 命令具有了 root 权限,但是没有让 “>” 和 “>>” 命令也具有 root 权限,所以 bash 会认为这个命令都没有向 test.txt 写入的权限

这时候,bash -c 就可以出场了,它可以让 bash 将一个字串作为完整的命令来执行,这样就可以将 sudo 的影响范围扩展到整条命令

1
$ sudo bash -c "echo 'test' >> test.txt"

be slow to promise and quick to perform.