Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' 
like image 482
Steffen Avatar asked Jul 26 '16 16:07

Steffen


People also ask

How do you write a one line function?

Here's the most Pythonic way to write a function in a single line of code: f2 = lambda x: str(x * 3) + '! ' You create a lambda function and assign the new function object to the variable f2 .

Should a function be one line?

It depends on the line of code. If the line of code is just calling another function, then wrapping that in another function doesn't make sense. If it's some complicated line that has lots of parts subject to change, then it might make sense.

How do you define a function in Python?

Basic Syntax for Defining a Function in Python In Python, you define a function with the def keyword, then write the function identifier (name) followed by parentheses and a colon. The next thing you have to do is make sure you indent with a tab or 4 spaces, and then specify what you want the function to do for you.

Are One line functions okay?

There is nothing wrong with one line functions. As mentioned it is possible for the compiler to inline the functions which will remove any performance penalty. Functions should also be preferred over macros as they are easier to debug, modify, read and less likely to have unintended side effects.


1 Answers

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%/*}" ; } 
like image 128
ruakh Avatar answered Sep 28 '22 21:09

ruakh