0

So far "ls" works fine i take all files in the directory. But now i want when i execute ./myscript ls -l /somedir to take the same results as i take when i type ls -l /somedir at the terminal.

Is there any way to make it? This is my code so far..

#!/bin/sh
clear

echo ""
read  -p "type something :  " file
    echo""
    IFS=:
    for dir in $PATH ; do  

        if [ -x "$dir/$file" ]
        then

        echo ""
          exec "$dir/$file" 

        fi
        done
18
  • You mean pipe the output of ls -1 somedir to yourscript.sh? e.g. ls -1 /somedir | sh yourscript.sh ? Commented Nov 10, 2015 at 22:43
  • I realise that the comments don't display properly, but can you try explaining, in words, what you're trying to achieve? Commented Nov 10, 2015 at 23:23
  • well my script can execute a program that is located at some directory of the $PATH by giving its name. Also by typing ls i take back the files of the directory. Now i want when i type ls -l / tmp to take as return what i would take by typing ls -l /tmp at user@user:~$ at my terminal. @aho Commented Nov 11, 2015 at 0:29
  • This is a bit confusing; perhaps it's a language barrier, perhaps it's you not quite understanding. If you type "ls -l /tmp" or "ls -l / tmp" at your terminal, your script will not be invoked. In order to invoke your script, you'd have to run your script. What is the name of the file in which your script is written? And how would you like to invoke it? Commented Nov 11, 2015 at 0:41
  • There's no point to launch a command into the background, and then the next thing you do is wait for it to finish. Commented Nov 11, 2015 at 0:55

1 Answer 1

2

As I understand it (which involves a great deal of guesswork, as the question is not clearly asked), your problem is that command-line arguments aren't passed through.

Use "$@" to access them:

#!/bin/bash
prog=$1; shift
IFS=: read -r -a paths <<<"$PATH"
for path in "${paths[@]}"; do
  [[ -x $path/$prog ]] && "$path/$prog" "$@"
done

Then, running yourscript ls -l /foo will actually pass the -l and the /foo through to any instance of ls they create.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.