简体   繁体   English

Shell Script Tilde扩展

[英]Shell Script Tilde Expansion

Here is my script: 这是我的脚本:

#!/bin/bash 
echo "Digite o local em que deseja instalar o IGRAFU(pressione enter para 
instalar em 
${HOME}/IGRAFO):"
read caminho
if test -z $caminho
then
caminho="${HOME}/IGRAFO"
fi
echo "O IGRAFU será instalado no diretório: $caminho"
mkdir -pv $caminho

mv -v ./* $caminho
echo "Pronto!"

At 'read caminho' I may receive from the user a path like ~/somefolder. 在'read caminho',我可能会从用户那里收到像〜/ somefolder这样的路径。 When the script receives that kind of path both mv and mkdir won't make tilde expansion, so it will try to create a ~/somefolder and not /home/username/somefolder and therefore fail. 当脚本收到那种路径时,mv和mkdir都不会进行代码扩展,所以它会尝试创建一个〜/ somefolder而不是/ home / username / somefolder,因此会失败。

How do I ensure that the tilde will be converted into the HOME variable? 如何确保波浪号将转换为HOME变量?

You will probably need to eval the variable to have it substituted correctly. 您可能需要评估变量才能正确替换它。 One example would be to simply do 一个例子就是简单地做

caminho=`eval "echo $caminho"`

Keep in mind that this will break if caminho contains semicolons or quotes, it will also treat backslashes as escaping, and if the data is untrusted, you need to take care that you're not the target of an injection attack. 请记住,如果caminho包含分号或引号,这将会中断,它也会将反斜杠视为转义,如果数据不受信任,则需要注意您不是注入攻击的目标。

Hope that helps. 希望有所帮助。

Quoting and expansion are always tricky, especially in bash. 引用和扩展总是很棘手,特别是在bash中。 If your own home directory is good enough, this code works (I have tested it): 如果你自己的主目录足够好,这段代码可以工作(我已经测试过了):

if test -z $caminho
then
caminho="${HOME}/IGRAFO"
else
  case "$caminho" in
    '~')   caminho="$HOME" ;;
    '~'/*) caminho="$HOME/${caminho#'~/'}" ;; 
    '~'*)  echo "Case of '$caminho' is not implemented" 1>&2 ;;
  esac
fi

如果不是/home也许使用/home/${USER}替换你的高用户级目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM