LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to handle parameters in a .bashrc function (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-handle-parameters-in-a-bashrc-function-4175533200/)

whim 02-05-2015 05:05 PM

How to handle parameters in a .bashrc function
 
I want to create a simple bash function (in .bashrc) that takes in one parameter (a directory name) and tars all the files inside of that directory into a specific directory in /home (we'll call that destdir). The name of the tar should be the same as the directory parameter.

For example, I want to be able to type into the terminal "task directory_name".

I tried this but it didn't work:

Code:

function_name() {
  cd $1
  tar czf /~/destdir/$1.tar *

  return 0
}
alias task=function_name

What am I doing wrong?

ulto 02-05-2015 06:49 PM

Try it by taking out the / in the /~/destdir part. ~/destdir should be sufficient.

Also, trying creating a shell script from that function and use bash -x to diagnose the issue further if the above doesn't help

Keith Hedger 02-05-2015 06:49 PM

Code:

function_name() {
cd $1
tar -czf ~/destdir/$1.tar.gz .
 }
alias task=function_name

Will cd into $1 then create an archive in ~/destdir.
N.B.
Won't handle folders with spaces in their names in ( that's for you too work out)
~/destdir must exist if it doesn't again for you to work out.
See the man page for tar an the advanced bash scripting guide for detailed help

Keith Hedger 02-05-2015 06:50 PM

Quote:

Originally Posted by ulto (Post 5312758)
Try it by taking out the / in the /~/destdir part. ~/destdir should be sufficient.

Sorry you posted while I was typing

ulto 02-05-2015 06:53 PM

SNAP! Ah no worries :)

rknichols 02-06-2015 07:58 AM

Code:

function_name() {
cd $1 || return 1
tar -czf ~/destdir/$1.tar.gz .
 }
alias task=function_name

If you type a wrong name and the cd fails, you really don't want tar acting in the old CWD.

Keith Hedger 02-06-2015 08:10 AM

Quote:

Originally Posted by rknichols (Post 5312991)
Code:

function_name() {
cd $1 || return 1
tar -czf ~/destdir/$1.tar.gz .
 }
alias task=function_name

If you type a wrong name and the cd fails, you really don't want tar acting in the old CWD.

+1
Yes lots of error checking can be done but leave something for the OP to do! :)

My excuse is I was typing on my tablet and couldn't actually test the code!


All times are GMT -5. The time now is 07:35 PM.