tags:

views:

709

answers:

3

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. 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.

How do I ensure that the tilde will be converted into the HOME variable?

+5  A: 

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.

Hope that helps.

roe
A: 

Maybe use /home/${USER} instead substituting your high user level directory if if isn't /home

HTH

cheers Rob

Rob Wells
Assuming all users home directories have a common parent directory is a very bad assumption.
Dave C
A: 

Quoting and expansion are always tricky, especially in 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
Norman Ramsey