user3726663
user3726663

Reputation: 1

Create alias for command containing single quotes

im trying to create alias for this command

for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done

Im using this command to create alias

alias renfiles="for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done"

But it creates alias for wrong command :

$ which renfiles
alias renfiles='for file in *; do mv * * ; done'

What i would like to do is to create one alias that rename files then list them using readlink, so one alias to do below :

for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done
for f in *; do   readlink -f -- "$f"; done | sed -e "s/\/home\/ovh\/www/xxx.xxx.xxx.xxx/g"

Upvotes: 0

Views: 72

Answers (2)

ilkkachu
ilkkachu

Reputation: 6527

alias renfiles="for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done"

1) You have two quoted strings there (marked), the expansion of $file is outside any quotes. Which means that it will be expanded when the alias is set, not when it's executed. (It would be expanded from within the double-quotes, too)

2) Backticks (as well as the saner $(...)) are expanded from inside double-quotes, so they also get expanded when the alias is set. So, if $file happened to contain a * when the alias was set, you'd get exactly what you saw.

If you want to do something like that with an alias, use single quotes around it:

alias renfiles='for file in *; do echo mv "$file" $(echo $file | tr " " "_") ; done'

(Or better yet, use a function like @chepner showed.)

Upvotes: 0

chepner
chepner

Reputation: 531255

Use a function instead:

renfiles () {
  for file in ./*; do
    mv "$file" "$(echo "$file" | tr ' ' '_')"
  done
}

You can write this more simply in bash as

renfiles () {
  for file in ./*; do
    mv "$file" "${file// /_}"
  done
}

Upvotes: 4

Related Questions