在shell脚本中将./替换为$PWD

kiayqfof  于 2023-02-24  发布在  Shell
关注(0)|答案(2)|浏览(155)

我有一个字符串可能以./开头,也可能不是,或者可能只是一个./在这种情况下,我想用$PWD替换它
有人帮忙吗?

APP_FOLDER=./service
MODIFIED_APP_FOLDER= = $([[ $APP_FOLDER= './'* ]] && echo "${APP_FOLDER/'./'/"$PWD"}" || echo "$PWD/$APP_FOLDER")

导致"错误替换"

ryhaxcpt

ryhaxcpt1#

这里不需要使用子shell扩展和Bash:

#!/usr/bin/env bash

printf '%-10s %s\n' 'app_folder' 'modified_app_folder'
for app_folder in ./service foobar ./ /tmp/test; do
    modified_app_folder=${app_folder/#.\//$PWD/}
    printf '%-10s %s\n' "$app_folder" "$modified_app_folder"
done

样本输出:

app_folder modified_app_folder
./service  /home/lea/StackOverflow/service
foobar     foobar
./         /home/lea/StackOverflow/
/tmp/test  /tmp/test
ukqbszuj

ukqbszuj2#

就像这样:
在请求人工帮助之前,请始终将脚本传递给https://shelcheck.net。或者使用命令行:

$ shellcheck file
In file line 2:
MODIFIED_APP_FOLDER= = $([[ $APP_FOLDER= './'* ]] && echo "${APP_FOLDER/'./'/"$PWD"}" || echo "$PWD/$APP_FOLDER")
                    ^-- SC1007 (warning): Remove space after = if trying to assign a value (for empty string, use var='' ... ).
                       ^-- SC1009 (info): The mentioned syntax error was in this command expansion.
                         ^-- SC1073 (error): Couldn't parse this test expression. Fix to allow more checks.
                                       ^-- SC1108 (error): You need a space before and after the = .
                                          ^-- SC1072 (error): Expected comparison operator (don't wrap commands in []/[[]]). Fix any mentioned problems and try again.

For more information:
  https://www.shellcheck.net/wiki/SC1108 -- You need a space before and after...
  https://www.shellcheck.net/wiki/SC1007 -- Remove space after = if trying to...
  https://www.shellcheck.net/wiki/SC1072 -- Expected comparison operator (don...

更正代码:

$ cat file
APP_FOLDER=./service
MODIFIED_APP_FOLDER=$([[ $APP_FOLDER == './'* ]] && echo "${APP_FOLDER/.\//"$PWD/"}" || echo "$PWD/$APP_FOLDER")
echo "$MODIFIED_APP_FOLDER"

$ bash file
/tmp/service

相关问题