Grep Loop Statements

Discussion in 'Mac Programming' started by gpchess2k, May 2, 2017.

  1. gpchess2k, May 2, 2017
    Last edited by a moderator: May 3, 2017

    gpchess2k macrumors newbie


    Oct 12, 2015
    Hello, I am looking for help on adding loop statements to my current working bash script. What the script does is look for a particular printer by protocol and remove it. What I would love to do is remove ALL printers found with that protocol. I have played with a few examples of 'while' and 'until' loop statements but can't seem to get it right. Code is a bit messy and I'm sure it can be simplified.

    printer1=$(lpstat -s | grep '' | awk -F'/' '{print $3}')
    printer01=$(lpstat -s | grep 'smb://' | awk -F'/' '{print $3}')
    if [ -z $printer1 ]; then
    remove_printer1=$(lpstat -s | grep '' | awk -F ' ' '{print $3}' | sed s/://g)
    lpadmin -x $remove_printer1
    remove_printer2=$(lpstat -s | grep 'lpd://' | awk -F ' ' '{print $3}' | sed s/://g)
    lpadmin -x $remove_printer2
    remove_printer3=$(lpstat -s | grep 'ipp://' | awk -F ' ' '{print $3}' | sed s/://g)
    lpadmin -x $remove_printer3
    if [ -z $printer01 ]; then
    remove_printer=$(lpstat -s | grep 'smb://' | awk -F ' ' '{print $3}' | sed s/://g)
    lpadmin -x $remove_printer4
  2. hughm123 macrumors newbie

    Dec 3, 2014
    In general you do something like the following. Be warned though: bash and other shells are extremely bad for this type of scripting because the script may break if you have printer names containing spaces or other special characters, because the shell expands the variables in line and then evaluates the statement. For example, the for loop below expects $remove_printers to expand to a space-separated list of printers from the grep command so a printer name containing spaces will be split. And a printer name containing "; do" would break the script. In some cases this may even cause security bugs if the script is privileged. So if at all possible use a better scripting languages like Perl which handles quoting more robustly.

    Having said that, loops in bash work this way:

    remove_printers=$(lpstat -c -v | grep '' | awk -F ' ' '{print $3}' | sed s/://g)
    for printer in $remove_printers ; do
    echo remove $printer

    I also replaced "lpstat -s" with "lpstat -c -v" to avoid printing a default line which might break the script.

Share This Page