Shell脚本中问号(?)的使用问题

huangapple go评论80阅读模式
英文:

Shell Script question mark (?) issue in its uses

问题

我正在尝试运行以下脚本,但遇到了一个问题。
我找到了解决方案,但仍然不清楚为什么这个解决方案有效。
我想了解其中的概念:

我的脚本:

#!/bin/bash
# 运行脚本

echo "请使用:nice nohup ./run_script 运行"

# 脚本存储的工作目录
WORKING_DIR=$(pwd)

# 用于构建和运行cmake ctest的临时目录
BUILD_DIR?=/localtemp/build

# 清理并创建构建目录
rm -rf $BUILD_DIR
mkdir -p $BUILD_DIR
mkdir -p $BUILD_DIR/../result

遇到错误:

BUILD_DIR?=/localtemp/build: 没有那个文件或目录
mkdir: 缺少操作数
请运行 'mkdir --help' 以获取更多信息。
mkdir: 无法创建目录 '/../result': 权限被拒绝

但是,如果我从BUILD_DIR?=/localtemp/build这行中删除?,将其改为BUILD_DIR=/localtemp/build,那么脚本可以正常运行。

我的假设:

我想在BUILD_DIR这一行中使用**"?"**,以便如果有人想从脚本外部设置BUILD_DIR,它可以采用外部路径。否则,默认情况下,它应该使用我脚本中提到的上面路径。

有人能够解释一下在Shell脚本中使用**"?"**的用法吗?

英文:

I am trying to run below script but facing an issue .
I got the solution but still why this solution is working that I Am not clear .
I want to know the concept behind this :

My script:

#!/bin/bash
# RUN script



echo "please run with: nice nohup ./run_script"

# working directory where script is stored
WORKING_DIR=$(pwd)

# temp directory to build and run the cmake ctest
BUILD_DIR?=/localtemp/build

# clean and make build directory
rm -rf $BUILD_DIR
mkdir -p $BUILD_DIR
mkdir -p $BUILD_DIR/../result

Getting error as :

BUILD_DIR?=/localtemp/build: No such file or directory
mkdir: missing operand
Try 'mkdir --help' for more information.
mkdir: cannot create directory ‘/../result’: Permission denied

But if I remove the "?" from the line BUILD_DIR?=/localtemp/build and making it BUILD_DIR=/localtemp/build, the scripts run fine .

My assumptions:

I want "?" with BUILD_DIR line as if some one wants to set the BUILD_DIR from outside the script it has to take the outside path. otherwise by default it has to go with the above path mentioned in my script .

Can anyone clear my doubt in the shell script about the "?" use

答案1

得分: 4

看起来你把Makefile的语法和bash的语法混淆了。表达式 ?= 不是有效的bash表达式。你可以改成这样写:

BUILD_DIR=${BUILD_DIR:-/localtemp/build}

这意味着如果BUILD_DIR已设置,就将BUILD_DIR设置为其值,否则设置为/localtemp/build

英文:

It looks like you're confusing Makefile syntax with bash syntax. The expression ?= isn't a valid bash expression. You can instead write something like this:

BUILD_DIR=${BUILD_DIR:-/localtemp/build}

Which means set BUILD_DIR to the value of BUILD_DIR, if it's set, otherwise to /localtemp/build.

huangapple
  • 本文由 发表于 2020年1月3日 23:07:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定