bash 用于将磁盘添加到 fstab(如果不存在)的脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32778125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:38:01  来源:igfitidea点击:

Script for adding a disk to fstab if not existing

bashpathgrep

提问by h0ch5tr4355

First of all, I have read many posts (see at bottom) with if-clauses to search in a file for a specific string and followed these posts 1to1, however I don't manage to get my script to work. I want to make an entry in /etc/fstabif it doesn't exist yet:

首先,我已经阅读了许多带有 if 子句的帖子(见底部)以在文件中搜索特定字符串并按照 1to1 的顺序关注这些帖子,但是我无法让我的脚本正常工作。/etc/fstab如果尚不存在,我想输入:

#!/bin/bash
fstab=/etc/fstab

if grep -q "poky-disc" "$fstab"
then
    echo "#poky-disc" >> /etc/fstab
    echo "/dev/sdb1 /media/poky ext4 defaults 0 2" >> /etc/fstab
else
    echo "Entry in fstab exists."
fi

Thanks for your help in advance. These are the similar posts, which didnt help me further:

提前感谢您的帮助。这些是类似的帖子,并没有进一步帮助我:

回答by tripleee

Here's a simple and hopefully idiomatic solution.

这是一个简单且希望是惯用的解决方案。

grep -q 'init-poky' /etc/fstab || 
printf '# init-poky\n/dev/sdb1    /media/poky    ext4    defaults    0    2\n' >> /etc/fstab

If the exit status from grep -qis false, execute the printf. The ||shorthand can be spelled out as

如果退出状态grep -qfalse,则执行printf. 该||速记可以拼写为

if grep -q 'ínit-poky' /etc/fstab; then
    : nothing
else
    printf ...
fi

Many beginners do not realize that the argument to ifis a command whose exit status determines whether the thenbranch or the elsebranch will be taken.

很多初学者没有意识到,to 的参数if是一个命令,它的退出状态决定了是then分支还是else分支被采用。

回答by Arunas Bartisius

Elegant and short way:

优雅而简短的方式:

#!/bin/bash
if ! grep -q 'init-poky' /etc/fstab ; then
    echo '# init-poky' >> /etc/fstab
    echo '/dev/sdb1    /media/poky    ext4    defaults    0    2' >> /etc/fstab
fi

It uses native Bash command exit code ($?=0 for success and >0 for error code) and if grep produces error, means NOT FOUND, it does inverse (!) of result, and adds fstab entry.

它使用本机 Bash 命令退出代码($?=0 表示成功,>0 表示错误代码),如果 grep 产生错误,则意味着未找到,它会反转 (!) 结果,并添加 fstab 条目。

回答by Noy Tsarfaty

I had the same issue. I managed to edit it with this command:

我遇到过同样的问题。我设法用这个命令编辑它:

sudo su -c "echo '#test' >> /etc/fstab"

回答by kyokose

#!/bin/bash
fstab=/etc/fstab

if [[ $(grep -q "poky-disc" "$fstab") ]]
# forgiving me for being a bit of over-rigorous, you might want to change this matching word, as below, 'poky-disc' merely a comment, not exactly a config line, so
then
    echo "#poky-disc" >> /etc/fstab
    echo "/dev/sdb1 /media/poky ext4 defaults 0 2" >> /etc/fstab
else
    echo "Entry in fstab exists."
fi