bash 使用参数和返回值在bash中执行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4470349/
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-09 19:58:38  来源:igfitidea点击:

Execute command in bash with parameter and return value

bashscripting

提问by Disco

I have the following script to check if a NFS mount is currently mounted on the server :

我有以下脚本来检查服务器上当前是否安装了 NFS 安装:

#!/bin/bash
$targetserver=192.168.3.1
commandline="mount | grep '$targetserver' | wc -l"
checkmount=`$commandline`

if [ $checkmount == "1" ]; then
  echo "Mounted !"
else
  echo "Not mounted"
fi

But it seems that my checkmount is not returning anything.

但似乎我的 checkmount 没有返回任何东西。

What am I missing here ?

我在这里错过了什么?

回答by jgr

This should work better.

这应该工作得更好。

#!/bin/bash
targetserver="192.168.3.1"
commandline=$(mount | grep "$targetserver" | wc -l)

if [ $commandline -gt 0 ]; then
  echo "Mounted !"
else
  echo "Not mounted"
fi

You could shorten it down though, using $?, redirection and control operators.

不过,您可以使用$?、重定向和控制运算符缩短它。

targetserver="192.168.3.1"
mount | grep "$targetserver" > /dev/null && echo "mounted" || echo "not mounted"

Depending on system grep /etc/mtabdirectly might be a good idea too. Not having to execute mountwould be cleaner imho.

grep /etc/mtab直接依赖于系统也可能是一个好主意。不必执行mount会更清洁恕我直言。

Cheers!

干杯!

回答by plundra

I'd maybe do this, or just but the content of the function directly in if, if you just use it in one place.

我可能会这样做,或者只是直接在 中的函数内容if,如果你只是在一个地方使用它。

nfsismounted() {
mount | grep -qm1 "":
}

q = quiet (we just want the return code), m1 = quit on first match.

q = 安静(我们只想要返回码),m1 = 在第一场比赛时退出。

And use it as such:

并使用它:

if nfsismounted 192.168.0.40; then
    echo "Mounts found"
else
    echo "Not mounts"
fi

A side note on the code in your question, you don't test with == in the shell, just =. == Will break on, for example, dash which is /bin/sh in Debian/Ubuntu since a while.

关于您问题中代码的旁注,您不在 shell 中使用 == 进行测试,而只是使用 =。== 将打破,例如,破折号,它是 Debian/Ubuntu 中的 /bin/sh 一段时间。

Edit: For added portability (non-GNU grep), remove the flags on grepand > /dev/null. Tests were done on bash/dash/ksh

编辑:为了增加可移植性(非 GNU grep),删除grep> /dev/null. 测试是在 bash/dash/ksh 上完成的