1

My question is about a script I was asked to write for college so it's H/W, but I am stuck and haven't figured out a solution.

I am trying to get the arguments of

./tool.sh -f persons.dat -id <id> 

because I want the in order to display the data of the person.

tool.sh is my program and persons.dat is a file with data of people that looks like this

3601|Wang|Lin|male|1981-01-02|2010-03-14T19:06:18.373+0000|1.10.108.68|Firefox

id|lastName|firstName|gender|birthday|creationDate|locationIP|browserUsed

I know I can't use getopts beacause id is a two letter flag and I could pass it manually but I am asked not to take the position in consideration so:

./tool.sh -f persons.dat -id <id> 

and:

./tool.sh -id <id> -f persons.dat

should be of the same use

Any ideas?

  • This is being flagged as off topic but I cannot see it as that, shell scripting is on topic here on unix.SE . Still I see a couple of issues with the question, the main one being the fact that you do not provide an excerpt of the script (or of how the script looks right now whilst not working). You certainly will need to use a case to parse the options, but you're probably doing it in some different way. – grochmal Oct 10 '16 at 7:50
  • -id would generally mean the same as -i -d. Making it -id understood as a single option would confuse your users especially if you also accept single-letter options. – Stéphane Chazelas Oct 10 '16 at 13:21
1

If your problem is limited to those 2 options, something of the like:

usage() {
echo "tools.sh -id <id> -f <file>"
echo "note: order of options is not important"

}

if [ $# -ne 4 ]; then
    echo "Wrong number of arguments"
    usage   
    exit 1
fi

if [ "$1" = "-f" -a "$3" = "-id" ]; then
    file="$2"
    id="$4"
elif [ "$1" = "-id" -a "$3" = "-f" ]
then
    file="$4"
    id="$2"
else
    echo "Wrong syntax!"
    usage
    exit 1
fi

Then, you can parse your file with awk:

awk -F'|' -v id="$id" '$1==id{printf "ID: "$1"\nUser: "$2" "$3"\nGender: "$4"\nBorn: "$5"\nCreation Date: "$6"\nLocation IP: "$7"\nBrowser used: "$8"\n"}' $file

if [ $? -eq 0 ]
then
    exit 0
else
    echo "Something went \"woopsie!\""
    exit 1
fi

To make it better, you could also check that id is a number and that persons.dat is indeed a file somewhere in your PATH...

| improve this answer | |
0
awk -F\| 'NR==1{
for(j=1;j<=NF;j++)
Arr[j]=$j;
next
}
{
printf("./tool.sh -f file --edit");
for(i=1;i<=NF;i++)
printf("%s %s ",Arr[i],$i)
}
{
printf("\n")
}' persons.dat
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.