Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Directory as an Argument in Bash

I am having trouble finding out how to set a directory as an argument in bash.

The directory I am trying to have as an argument is /home/rrodriguez/Documents/one.

Anywhere I try to look for an answer I see examples like dir = $1 but I cant seem to find an explanation of what this means or how to set it up so that it references my specific file location. Could anyone show me how to set up my variable for my path directory?

Adding my code for a better understanding of what im trying to do:

#!bin/bash

$1 == 'home/rrodriguez/Documents/one/'

dir = $1

touch -c $dir/*
ls -la $dir
wc$dir/* 
like image 729
Robert Avatar asked Mar 12 '15 19:03

Robert


People also ask

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

What does $_ mean in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails. $@


1 Answers

Consider:

#!bin/bash

dir=$1
touch -c "$dir"/*
ls -la "$dir"

This script takes one argument, a directory name, and touches files in that directory and then displays a directory listing. You can run it via:

bash script.sh 'home/rrodriguez/Documents/one/'

Since home/rrodriguez/Documents/one/ is the first argument to the script, it is assigned to $1 in the script.

Notes

In shell, never put spaces on either side of the = in an assignment.

I omitted the line wc$dir/* because it wasn't clear to me what the purpose of it was.

I put double-quotes around $dir to prevent the shell from, among other things, performing word-splitting. This would matter if dir contains spaces.

like image 109
John1024 Avatar answered Sep 22 '22 23:09

John1024