I wrote a script in bash to basically create aliases, but for any reason, it doesn't work in some cases. Here it's the code:
#!/bin/bash
#Script to create unique and permanent aliases
_add_alias()
{
echo "alias $1='$2'" | sudo tee -a $HOME/.bash_aliases
echo "Alias successfully created"
}
if [ `cat $HOME/.bash_aliases | grep "alias $1=" | wc -l` == 0 ]
then
if [ $# -eq 2 ]
then
if [ -f "$2" ] #This condition is always false, don't know why.
then
_add_alias $1 "$2"
elif $2 > tmp.txt 2> tmp.txt
then
_add_alias $1 "$2"
else
echo "Wrong command"
fi
rm tmp.txt
elif [ $# -gt 2 ]
then
echo "Error: Usage: addal alias_name 'command' (comand between quotes)"
elif [ $# -lt 2 ]
then
echo "Wrong number of parameters"
fi
else
echo "Alias name already exists"
fi
I hope you could help me fix the script.
[ -f $2 ]
- do you expect$2
to be a path to some file? 2.sudo tee -a
? You don't needsudo
to write to your own home folder unless your permissions are messed up. 3. You could replace that big if condition with:if ! grep -q "alias $1=" $HOME/.bash_aliases"; then
. – muru Apr 14 '15 at 11:24<your_script> rm "rm -rf /"
. – A.B. Apr 14 '15 at 12:01--no-preserve-root
option. – 0x2b3bfa0 Apr 14 '15 at 13:48.bash_aliases
file with these commands:sudo chown $USER:$USER ~/.bash_aliases
andchmod go=,u=rwx .bash_aliases
– 0x2b3bfa0 Apr 14 '15 at 14:36