Adding option to my commands.

p4p1 [lexostras]
9 years ago

0

Hello, me again :P. So after making my own linux command that is cls (thx @dloser for the name :D ) I wanted to add options like -h to improve it but I have no idea how to do it.
My command is more of a bash script, here it is (the source code):
```

!/bin/sh

clear && ls –color
```
I saved this file in /sbin and added the chmod 755 to run it thx to @souvarine .
So if you don’t still understand this post, I am asking on how to add a -h option to my command without making a whole new thing.

5replies
3voices
201views
? [bolofecal]
9 years ago

0

```#!/bin/sh

until [ -z “$1” ]; do
if [ $1 = ‘-h’ ] || [ $1 = ‘–help’ ]; then
echo “put your text here”
exit 0
fi
shift
done

clear && ls –color```

? [bolofecal]
9 years ago | edited 9 years ago

0

You can increase others arguments like this:

```#!/bin/sh

until [ -z “$1” ]; do
if [ $1 = ‘-h’ ] || [ $1 = ‘–help’ ]; then
echo “put your text here”
exit 0
elif [ $1 = ‘-a’ ] || [ $1 = ‘–all’ ]; then
clear && ls -a –color
exit 0
else
echo “Unknow option \”$1\“”
exit 1
fi
shift
done

clear && ls –color```

$1 -> argument 1
$2 -> argument 2

This command takes one argument, a number. The positional parameters are shifted to the left by this number.

e.g.

yourcommand 1 2 3
shift
yourcommand 2 3
shift
yourcommand 3
shift
yourcommand

Mart
9 years ago

0

if you only want to add one or two flags that is ok but really you want to use “getopt” or similar

p4p1 [lexostras]
9 years ago | edited 9 years ago

0

thank you @Mart but I am not great in C for now :) I am actually learning it right now lol oh my bad, is getotp just for C or isnt it a thing to pass arguments in shell scripts??

Mart
9 years ago

0

getopt exists as a shell command, use “man getopt” to see what it does.

There are plenty of online tutorials for using it, e.g. http://wiki.bash-hackers.org/howto/getopts_tutorial

You must be logged in to reply to this discussion. Login
1 of 6

This site only uses cookies that are essential for the functionality of this website. Cookies are not used for tracking or marketing purposes.

By using our site, you acknowledge that you have read and understand our Privacy Policy, and Terms of Service.

Dismiss