martinuz99
martinuz99

Reputation: 3

Output of a command in a bash script is different from normal command

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.

Upvotes: 0

Views: 218

Answers (1)

tripleee
tripleee

Reputation: 189387

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.

Upvotes: 1

Related Questions