0

i am using opensuse as a virtual machine on my laptop. this question is about code that i need to do for my homework.

I need to make a script with a variable that shows the amount of entries in a directory.

when i write the exact command in a bash script the output is diffrent from when i run it directly from the CLI

#! /bin/bash

clear

ENTRIES=$(ls /tmp | wc -l)

echo "the amount of entries is" "$ENTRIES"

When i run this script the output will be 53

but when i type the command "ls /tmp | wc -l" in the terminal/CLI i get 61

does anyone know how to solve/explain this?

I got confused and went to look online for answers but I could not find any that's why I am asking this question

thanks for the effort

Sorry for any spelling mistakes. I‘m from the Netherlands.

9
  • Are the results consistent? Anything could be creating files in /tmp; the difference could simply be due to when you ran the command versus any differences between a script and the interactive prompt. Commented Apr 1, 2019 at 18:01
  • I changed the folder to "/home/jan" in the script and in the normal command. the output of the script is 2 but the output of the normal command is 13 Commented Apr 1, 2019 at 18:07
  • 1
    Well, what are the actual contents of the directory? Also, do you have any aliases like alias ls='ls -a'? Aliases won't be set or expanded for your script. Commented Apr 1, 2019 at 18:13
  • (Comparing the output of ls /home/jan itself in both settings should help clear this up as well. If you don't understand the counts, look at what's actually being counted.) Commented Apr 1, 2019 at 18:14
  • 1
    maybe its something with permissions? Commented Apr 1, 2019 at 18:21

1 Answer 1

1

The command substitution might be implemented in a way which creates a temporary file.

More likely, the number of files in /tmp naturally varies over time, and you postulate a causation where there just happened to be a correlation.

A better way to implement this avoids parsing ls output using either an array

#!/bin/bash
tmpfiles=(/tmp/*)
echo "$(#tmpfiles[@]} files in /tmp"

or just enumerating the files, which is portable to POSIX sh:

#!/bin/sh
set -- /tmp/*
echo "$# files in /tmp"

Printing out the array or list of arguments should reveal which files exactly were present.

As an aside, don't use upper case for your private variables; uppercase variable names are reserved for system variables.

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.