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?
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.
~/ (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.
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.
: a drawing showing the shell plating of a ship and giving the size, shape, and weight of the plates and their connections.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With