I used following piece of code to list down the contents of a directory in macOS:


echo "hello User"
echo ""
var_one=$userdir\/Library\/Application\ Support\/iCloud\/Accounts\/
    if [ -d "$var_one" ]
        # echo "Direcotry exists"
        echo "The AppleID is : "
        sed -n '/[*\w-]+@([\w-]+\.)+[\w-]+/p'|ls "$var_one"|awk NR==2'{print}'
        echo "~~~~~~~BYE~~~~~~" 
        echo "Directory doesn't exists" 
        echo "The path is $var_one"

If the directory exists then sed command is used along with regex pattern to identify the desired file. The script works fine but doesn't seem to exit.

  • 1
    there is no input to sed command, sed is waiting on STDIN – Archemar Mar 27 '19 at 5:56
  • Few comments: * You dont need to escape the /. You just need to escape the spaces. * break is only valid in loops. – Mike V.D.C. Mar 27 '19 at 6:36
  • 1
    Also, if you're on macOS, sed is unlikely to know what \w is (macOS sed does not know PCRE expressions). Instead, use [[:alnum:]_] (this is a POSIX character class equivalent to \w). – Kusalananda Mar 27 '19 at 6:50

There's a few things that could be improved in your script.

First of all, the sed doesn't do anything because it's not receiving any input. This means that it will just sit there waiting for you to type things on the keyboard into its standard input stream. Additionally, don't use sed or other text editing tools (awk etc.) on filenames. Filenames on Unix systems can, contain newlines, and sed (for example) reads individual lines, which means it would read a filename with an embedded newline as two separate things.

It's uncommon for filenames to contain newlines, but if a script don't take this into account, a malicious user may possibly use this fact to confuse the script into doing things it wasn't designed to do.

To find the currently signed in Apple ID, rather than using some heuristic approach, use a tool that can do it for you. With Homebrew, you may install mas:

brew install mas


mas account

will give you the currently signed in Apple ID.

| improve this answer | |

Try replacing:

sed -n '/[*\w-]+@([\w-]+\.)+[\w-]+/p'|ls "$var_one"|awk NR==2'{print}'

With something like this:

ls "$var_one" | sed -n '2{/[*\w-]+@([\w-]+\.)+[\w-]+/p}'

See also: Why not parse ls (and what do to instead)?

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.