Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script Tilde Expansion

Tags:

linux

shell

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?

like image 798
Diones Avatar asked Jan 17 '09 17:01

Diones


People also ask

What does tilde expand to?

Tilde expansion applies to the ' ~ ' plus all following characters up to whitespace or a slash. It takes place only at the beginning of a word, and only if none of the characters to be transformed is quoted in any way. Plain ' ~ ' uses the value of the environment variable HOME as the proper home directory name.

What is tilde in shell script?

~/ (tilde slash) The tilde (~) is a Linux "shortcut" to denote a user's home directory. Thus tilde slash (~/) is the beginning of a path to a file or directory below the user's home directory. For example, for user01, file /home/user01/test. file can also be denoted by ~/test.

Can I use tilde in bash script?

Bash also performs tilde expansion on words satisfying the conditions of variable assignments (see Shell Parameters) when they appear as arguments to simple commands. Bash does not do this, except for the declaration commands listed above, when in POSIX mode.

What is expansion in shell?

: a drawing showing the shell plating of a ship and giving the size, shape, and weight of the plates and their connections.


2 Answers

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.

like image 144
falstro Avatar answered Oct 16 '22 08:10

falstro


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
like image 2
Norman Ramsey Avatar answered Oct 16 '22 08:10

Norman Ramsey