1

I have cp and mv commands withaliases preset in my system.

[root@IMSSA ~]# which cp mv
alias cp='cp -i'
        /bin/cp
alias mv='mv -i'
        /bin/mv
[root@IMSSA ~]#

If I try to replace a file, it will ask for prompt when try in command line.

But when I use a same within a script, they won't ask for prompt and just replaces the file.

[root@IMSSA ~]# echo "t giv" > /tmp/givin.txt; echo "r giv" > /root/givin.txt
[root@IMSSA ~]# cat /tmp/givin.txt /root/givin.txt
t giv
r giv
[root@IMSSA ~]# cat /tmp/givi.sh
mv /root/givin.txt /tmp/givin.txt
[root@IMSSA ~]#


[root@IMSSA ~]# mv /root/givin.txt /tmp/givin.txt
mv: overwrite '/tmp/givin.txt'? ^C               ### Used ^C to cancel the Operation.
[root@IMSSA ~]# 


[root@IMSSA ~]# sh -x /tmp/givi.sh
+ mv /root/givin.txt /tmp/givin.txt
[root@IMSSA ~]# cat /tmp/givin.txt /root/givin.txt
r giv
cat: /root/givin.txt: No such file or directory
[root@IMSSA ~]#

So the aliases are not used inside the script, but why bash script and command prompt have different env? How does alias work here?

EDIT: This answers the question.

Why doesn't my Bash script recognize aliases?

prado
  • 930
  • 1
  • 11
  • 33
  • the script probably has no aliases set. Add the option -i to the calls in the script. If necessary rewrite your script to accept an option to move with or without interaction. – ruud Jun 02 '20 at 12:34
  • @ruud yes, if I use which cp mv inside the script, it will not show the alias, but the question is why alias is not taking? I will update the question more clearly. – prado Jun 02 '20 at 12:38
  • 1
    prado, it is better not to rely on externally set aliases in a script altogether. If you want to influence the behaviour of your script, don't do that by changing aliases, but do this by logic in the script itself. – ruud Jun 02 '20 at 12:47
  • 1
    It is a lethal security risk for a script to trust existing aliases. Consider the effect of a malicious agent declaring alias ls='rm -rf .' before running a sudo script, for example. – Paul_Pedant Jun 02 '20 at 17:09

0 Answers0