我通常会留在 StackOverflow 上,但我认为在这个主题上,你们是这里的专家。
所以今天的练习很奇怪,我必须写一个script.sh
并在其中尽我所能防止test.txt
被删除但问题是最后一行必须是
rm -f test.txt
Run Code Online (Sandbox Code Playgroud)
我对 shell 不太了解(我通常做 c/objective-c),所以我拿起一本书,还没读完,但仍然不知道如何去做。
我考虑过权限,但脚本在测试时将获得所有权限,所以它不是一个选项......(我不知道这是否重要,但脚本将在 OS X 上运行)。
在 Linux 上,您可以使用不可变标志 usingchattr
来实现文件系统级别的只读(尽管需要适当的权限)。我不使用 OS X,不知道它是否有类似的东西,但是您可以使用以下方法实现“脚本运行后,test.txt
仍然存在”:
#!/bin/sh
mv test.txt test.bak
trap "mv test.bak test.txt" EXIT
rm -f test.txt
Run Code Online (Sandbox Code Playgroud)
当脚本退出时(在 之后),此脚本将重命名test.txt
为test.bak
并重命名回rm -f test.txt
。这不是真正的只读,但除非你是kill -KILL
你的脚本,否则它至少应该保留你的数据。
另一种想法,如果您坚持在其中包含该行,为什么不早点退出?
#!/bin/sh
# do your thing
exit
# my boss insisted to have the 'rm' line below.
rm -f test.txt
Run Code Online (Sandbox Code Playgroud)
rm
变成一个什么都不做的函数的替代方案:
#!/bin/sh
# do your thing
rm() {
# this function does absolutely nothing
: # ... but it has to contain something
}
rm -f test.txt
Run Code Online (Sandbox Code Playgroud)
与上面的函数方法类似,但使用已弃用的alias
命令将别名rm
设置true
为什么都不做的内置函数(但返回一个真正的退出代码):
#!/bin/sh
# do your thing
alias rm=true
rm -f test.txt
Run Code Online (Sandbox Code Playgroud)
rm
从环境中删除的替代方案(假设没有rm
内置):
#!/bin/sh
# do your thing
PATH= # now all programs are gone, mwuahaha
# gives error: bash: rm: No such file or directory
rm -f test.txt
Run Code Online (Sandbox Code Playgroud)
另一个$PATH
通过使用存根rm
程序(/tmp
用作搜索路径)进行更改:
#!/bin/sh
# do your thing
>/tmp/rm # create an empty "rm" file
chmod +x /tmp/rm
PATH=/tmp
rm -f test.txt
Run Code Online (Sandbox Code Playgroud)
有关内置函数的更多信息,请运行help <built-in>
以获取详细信息。例如:
true: true
Return a successful result.
Exit Status:
Always succeeds.
Run Code Online (Sandbox Code Playgroud)
对于其他命令,请使用man rm
或查看手册页man bash
.
归档时间: |
|
查看次数: |
3144 次 |
最近记录: |