Ubuntu Bash Script Advice?

1 replies
Im learning Bash Bourne Again Shell and I learned about the read command and I have problems with arrow key inputs. I could benefit from a web resource listing all the commands so I decided to make a script but I want to improve it.

So far I got this
apropos man > $HOME/Downloads/fcList.txt
cd $HOME/Downloads/
shuf -n 1 fcList.txt

this returns some of the commands randomly like i didnt see shuf in the list I want to grep this data to get the string up to the first space and then man $X that so it will output the man page for the command.

Eventually I think this script should come with linux I call it ranman It will get a random linux command and search the man pages for it.
#advice #bash #script #ubuntu
Avatar of Unregistered
  • Profile picture of the author AvoAvocado
    1. There are things called "pipes". They allow you to feed the output of one command as input to another one. This will allow you to avoid using an intermediate file ("fcList.txt" in your case) and simply do this:

    apropos man | shuf -n 1

    2. Extracting a string up to the first space can be done, as you mentioned, with "grep". Hint: you can use pipes as many times as you want.

    apropos man | shuf -n 1 | grep -E -o '^[^ ,\(]+'
    If you look at the man page of "grep", you'll see that "-E" stands for "extended regular expression", and "-o" stands for printing only the matching piece.
    This particular regexp takes everything from the beginning of the line, which is not a space, a comma, or a parenthesis. This way you get the exact string, which you can pass to the "man" command.

    3. Next, if you want to run the "man" command on the resulting string, you can either store it in a variable, or pass it directly to "man":

    # With a variable
    CMD=$(apropos man | shuf -n 1 | grep -E -o '^[^ ,\(]+')
    man $CMD
    # Or directly
    man $(apropos man | shuf -n 1 | grep -E -o '^[^ ,\(]+')

    4. Things in parentheses are actually important, because they provide you with different documentation on items with the same names. For me "apropos man" outputs two different lines about "tar" command:

    $ apropos man | grep '^tar'
    tar(1)                   - manipulate tape archives
    tar(n)                   - Tar file creation, extraction & manipulation
    Then running "man 1 tar" and "man n tar" gives me different man pages.
    You can extract those things from parentheses with "grep" or "sed", but I'm not going to go there.

    5. If you're learning about various linux commands, you might want to check out the website https://tldr.sh (it's not mine)

    6. If you're looking for a list of all commands, you might want to try "compgen -c" (https://stackoverflow.com/a/949006), as "apropos" not only doesn't seem to return everything, but also lists some C and Perl functions, which aren't very helpful in Bash.

    Good luck.
    {{ DiscussionBoard.errors[11444463].message }}

Trending Topics