Using GetOpts and error handling
Hi All,
I learning bash scripting and this time I trying to write a script that accepts a folder path (-P) and a file name (-N) then check if this file exists in the folder path specified. I'm using /home/chrisqck/Scripting/sometextfile.txt to test the script. I'm having a problem where if I run the script with -P then -N it will work beautifully. However if i swap the switches, -N first then -P the script will error out. I know there's a "logic flow" problem but for the life of me, i just can't figure out how else to do this. Is there a way for me to do for -N : If [[ -z $FolderPath ]] then "jump to -P then jump back to -N" else proceed with -N ? If not, how should i reqork the 'logic' of this script ? Here is the script : Code:
FolderPath="" # Default to empty path Any advice / guidance is much appreciated. Thanks in advance. |
only set the variables as you parse the options. Do the logic tests after all the options have been read.
|
Your possible options are:
Use one option for both /path/filename Do not check for a valid path/filename until after the while loop. Since both P and N require arguments exit the program in the loop if no argument provided i.e. either at :) or ?) |
yes, the general way is first check the arguments only, and validate them after the while loop.
Otherwise you may try shellcheck to help fix issues. |
Hi All,
I've been tied up with other critical task the pst couple of days. Just wanna drop in and thank everyone for the recommendations and guidance. Will work on the script and update once done. Much thanks ~!!! :D |
Quote:
test1.sh Code:
#!/usr/bin/bash Code:
bash ./test1.sh -P x -N x -H x This will get them in any order. test2.sh Code:
#!/usr/bin/bash Code:
bash ./test2.sh -N x -P x -H x |
Follow up.
test3.sh Code:
#!/usr/bin/bash Code:
bash ./test3.sh -N cow -P cat -H dog |
Hi All,
Again, I want to thank everyone for the tips and guidance. This script I wanted to learn how to use GetOpts. The function of the script is simply to check and let the person running it know if a specific file exists in a specific folder. The biggest mistake I made, I've learnt, was trying to fit in too many things in the GetOpt. What I should've done was to use it to just get the arguments then assign it to the correct variable and proceed from there. As the common practice in forums, I'm sharing my final script that I've been working on the couple of day. I'm sure someone here can make it even more efficient. As a newbie in this, I'm a little proud of that part that checks if the given path ends with "/" :D This has been an interesting lesson and I've learnt so much more than I thought I would. Code:
|
All times are GMT -5. The time now is 06:44 PM. |