0
#! /usr/bin/bash
for var in "$@"
do
    echo $var
done

simple shell script which displays each of the command line arguments, one at a time and stops displaying command line arguments when it gets an argument whose value is “stop”.?

stark
  • 12,615
  • 3
  • 33
  • 50

2 Answers2

0

IIUC, try this:

#!/bin/bash
for var in "$@"
do 
    if [[ "$var" == 'stop' ]]; then
        exit 0
    else
        echo "$var"
    fi
done
Victor Lee
  • 2,467
  • 3
  • 19
  • 37
  • `echo $var` is buggy. See [I just assigned a variable but `echo $variable` shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy May 27 '22 at 13:19
  • THX, have update it. – Victor Lee May 28 '22 at 01:23
0

Process args with a while loop:

#!/usr/bin/env bash

while test -n "$1"; do
    test "$1" != 'stop' && echo "$1" && shift || break
done
Cole Tierney
  • 9,571
  • 1
  • 27
  • 35
  • `foo && bar || baz` is not identical to `if foo; then bar; else baz; fi`. Better to do the latter and avoid corner cases. – Charles Duffy May 28 '22 at 01:25
  • A chain of "and" conditions can be followed by an "else" in my experience. Just short hand. I suppose `if then else` is more readable. Can you show me a corner case where my solution fails? – Cole Tierney May 28 '22 at 01:42
  • Sure. In `foo && bar || baz` it's possible for `baz` to run even if `foo` succeeded, should `bar` have a nonzero exit status. (In this case that would mean the write to stdout failing). – Charles Duffy May 28 '22 at 16:57
  • If you run your code through [shellcheck](https://www.shellcheck.net/), the warning it throws is [SC2015](https://www.shellcheck.net/wiki/SC2015). – Charles Duffy May 28 '22 at 17:00
  • Thank you, Charles. I'll run some tests. – Cole Tierney May 29 '22 at 07:18
  • `true && true || echo 'false'` `A` is a simple true or false, so I'm not worried about that corner case. – Cole Tierney May 29 '22 at 07:34
  • Sure, but the point I made is that `echo "$1"` is not _always_ true. It's _very usually_ true, but relying on that means that in the presence of bugs ("environmental surprises"?) impacting ability to write to stdout, you get _additional_ bugs whereby unexpected codepaths get executed. – Charles Duffy May 29 '22 at 14:10