Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

bash - How to define a function on one line

Often when moving files around, I need to do the opposite later. So in my .bashrc I included this working code:

rmv() {
  mv $2/${1##*/} ${1%/*}
}

Now I wonder why I can't write this as a single liner. This is what I tried:

rmv() {mv $2/${1##*/} ${1%/*}}

If I do so, I get this error:

-bash: .bashrc: line 1: syntax error near unexpected token `{mv'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Bash, { is not automatically recognized as a special/separate token from what's around it. So you need whitespace between { and mv.

Additionally:

  • } needs to be the start of a command; so if it's not on its own line, you need ; to terminate the previous command.
  • It's a best practice to always use double-quotes around any parameter expansion, since otherwise you'll get bizarre behaviors when the parameters include whitespace or special characters.

So:

rmv() { mv "$2/${1##*/}" "${1%/*}" ; }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...