0

I'm currently working on a BASH script (unable to post as it's graded, however we are allowed to ask for GUIDANCE) and I've nearly completed it.

It uses the ls command a lot, and we need to make it so the user can choose whether or not they want the ls command to include human readable format of sizes or not. (i.e whether ls includes -h).

I was wondering, is there a way to make it so that if the second argument of the script execution is -h, that all ls commands will include the -h option?

Cheers!

1
  • 1
    man getopt is your answer Commented Dec 19, 2013 at 18:34

3 Answers 3

1

The most simplistic way of doing this is

#!/bin/bash
if [[ $1 == -h ]]
then
  flags="-h"
else
  flags=""
fi

ls -l $flags

You could then run

./yourscript -h
./yourscript

and it would run ls with and without -h respectively.

More robust solutions for parsing flags include getopts, which allow you to parse conventional Unix flag specifications like ./yourscript -e foo -d bar -vhq. If you want your script to allow more than this single argument, you should look into that.

Sign up to request clarification or add additional context in comments.

1 Comment

So, say I had a .txt file with the following information in columns Size1 File1 Size2 File2 etc, How would I access the sizes, make them into human readable and replace all the sizes needed in the .txt file with the NEW sizes?
0

If you're iterating over the results of ls, you need to read http://mywiki.wooledge.org/ParsingLs . If you're using ls just to display files, you're OK.

To do option parsing in your script, use the bash builtin getopts -- search for getopts here and I'm sure you find lots of examples.

Comments

0

try something like :

human=${option+-$option}
ls $human
example :
option="h"
echo ls $human 
ls -h

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.