"Command not found" piping a variable to cut when output stored in a variable [duplicate]

Asked
Active3 hr before
Viewed126 times

7 Answers

90%

You need to pass an input string to the shell command using a pipeline in which case cut or any standard shell commands, reads from stdin and acts on it. Some of the ways you can do this are use a pipe-line, BTW, I'd suggest MY_DIR2=${MY_DIR%/*/*/*} -- much more efficient than using sed. (Also, all-caps variable names are used by the shell and OS -- using lowercase names for your own variables avoids conflicts; see pubs.opengroup.org/onlinepubs/9699919799/basedefs/…, fourth paragraph). – Charles Duffy Nov 14 '17 at 12:47 , Closed as dupe since the issue is (basically) that while you remembered the need to use echo on the standalone command, you forgot it in the command substitution -- so the problem, and the fix, is the same as in the flagged question. – Charles Duffy Nov 14 '17 at 12:57 , By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

You need to pass an input string to the shell command using a pipeline in which case cut or any standard shell commands, reads from stdin and acts on it. Some of the ways you can do this are use a pipe-line

dir2 = $(echo "$MY_DIR" | cut - d '/' - f - 4)

(or) use a here-string which is a shell built-in instead of launching a external shell process

dir2 = $(cut - d '/' - f - 4 << < "$MY_DIR")
load more v
88%

It is not working. I use the above code in a script and when I tried to echo, I am getting "command not found" error in the first line. – Ramesh Jan 29 '14 at 20:56 ,To capture the result of a command in a variable, you can use backticks (``) or, better, $(command). In your case, that would be:, What happens to my candy-creatures when they get wet and how do I stop it? , Stack Exchange network consists of 178 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Let's say each row has a unique ID, which makes things faster.

#!/bin/sh

NUM = 10
RESULTS = /tmp/results.$$.$RANDOM.txt

# Select some rows, selecting ID and URL

# The URL may contain spaces or single quotes.
# I wouldn 't trust double quotes; a  ` grep -v '
"'  ` piped between
# the mysql--silent and the
while could be advisable in this
case.

echo "SELECT id, url FROM mytable WHERE status = 0 LIMIT $NUM;"\ |
   mysql--silent mydatabase\ |
   while [-n "$ID"];
do
   read ID URL
if [-n "$ID"];
then
# Extract HTTP result code
CODE = ` curl -s --head "$URL" | head -n 1 \
                   | grep "^HTTP/[01]\.[0-9] [1-9][0-9]*" \
                   | cut -f2 -d" " `

# If there is a code
if [-n "$CODE"];
then
if ["$CODE" == "200"];
then
echo "200"
else
   echo "Not 200"
fi
# Prepare update
echo "UPDATE mytable SET status=$CODE WHERE id=$ID;" >> $RESULTS
else
   # We might update this ID to a new status in order not to
# extract it again.
echo "UPDATE mytable SET status=666 WHERE id=$ID;" >> $RESULTS
fi
fi
done

# update database
mysql mydatabase < $RESULTS
# Remove temporary file
rm $RESULTS
load more v
72%

When i know that i set the $CMD variable correctly (i tried the command outside the bash script and it worked just fine), Stack Exchange network consists of 178 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. ,fixed the bash so theres no spaces in the $CMD variable and put '' around it but now i'm getting the error file no such file or directory i looked at the path and copied it letter for letter and its correct.,To create a variable with the output of a command you may use $(command). This will execute command and return its output.

Working example

#!/bin/bash

CMD = "$(md5sum ../Desktop/cases/CourseworkCase/Evidence/image.dd)"
echo $CMD

To assign a variable never put a $ sign before nor spaces around the equal sign. The variable assignment in bash is like this:

MYVAR = "CONTENT"

The output of md5sum will be like this:

f110abe5b3cfd324c2e5128eb4733879 image.dd

If do you want to isolate the md5 sum of the file name, you can use one of these lines instead:

CMD = "$(md5sum ../Desktop/cases/CourseworkCase/Evidence/image.dd | cut -d ' ' -f 1)"
CMD = ($(md5sum.. / Desktop / cases / CourseworkCase / Evidence / image.dd))
load more v
65%

There is a typo in the makefile. Either make is looking for the wrong file or the rule to update the file specifies the wrong file. Typos can be hard to find in makefiles due to the use of make variables. Sometimes the only way to really be sure of the value of a complex filename is to print it out either by printing the variable directly or examining make’s internal database.,Debugging makefiles is somewhat of a black art. Unfortunately, there is no such thing as a makefile debugger to examine how a particular rule is being evaluated or a variable expanded. Instead, most debugging is performed with simple print statements and by inspection of the makefile. GNU make provides some help with various built-in functions and command-line options.,Basic debugging is the least detailed. When enabled, make prints each target that is found to be out-of-date and the status of the update action. Sample output looks like:,For makefiles that make extensive use of user-defined functions and eval to create complex variables and rules, examining this output is often the only way to verify that macro expansion has generated the expected values.

$(warning A top - level warning)

FOO: = $(warning Right - hand side of a simple variable) bar
BAZ = $(warning Right - hand side of a recursive variable) boo

$(warning A target) target: $(warning In a prerequisite list) makefile $(BAZ)
$(warning In a command script)
ls
$(BAZ):
$ make
makefile: 1: A top - level warning
makefile: 2: Right - hand side of a simple variable
makefile: 5: A target
makefile: 5: In a prerequisite list
makefile: 5: Right - hand side of a recursive variable
makefile: 8: Right - hand side of a recursive variable
makefile: 6: In a command script
ls
makefile
REQUIRED_DIRS = ...
   _MKDIRS: = $(shell
      for d in $(REQUIRED_DIRS);\ do\
         [
            [-d $$d]
         ] || mkdir - p $$d;\
      done)

$(objects): $(sources)
# GNU Make 3.80
# Copyright(C) 2002 Free Software Foundation, Inc.
# This is free software;
see the source
for copying conditions.
# There is NO warranty;
not even
for MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
normal command execution occurs here

# Make data base, printed on Thu Apr 29 20: 58: 13 2004

# Variables
   ...
   # Directories
   ...
   # Implicit Rules
   ...
   # Pattern - specific variable values
   ...
   # Files
   ...
   # VPATH Search Paths
# automatic
   <
   D = $(patsubst % /,%,$(dir $<))
      # environment EMACS_DIR = C: /usr/emacs - 21.3 .50 .7 #
      default CWEAVE = cweave # makefile(from `../mp3_player/makefile', line 35)
CPPFLAGS = $(addprefix -I ,$(include_dirs))
# makefile (from `.. / ch07 - separate - binaries / makefile ', line 44)
         RM: = rm - f # makefile(from `../mp3_player/makefile', line 14)
define make-library
  libraries += $1
  sources   += $2

  $1: $(call source-to-object,$2)
        $(AR) $(ARFLAGS) $$@ $$^
endef
% .c % .h: % .y
# commands to execute(from `../mp3_player/makefile', line 73):
        $(YACC.y) --defines $<
        $(MV) y.tab.c $*.c
        $(MV) y.tab.h $*.h

%: %.c
#  commands to execute (built-in):
        $(LINK.c) $^ $(LOADLIBES) $(LDLIBS) -o $@

%.o: %.c
#  commands to execute (built-in):
        $(COMPILE.c) $(OUTPUT_OPTION) $<
% .c % .h: YYLEXFLAG: = -d %
   .c % .h: % .y
$(YACC.y) --defines $ <
   $(MV) y.tab.c $ * .c
$(MV) y.tab.h $ * .h
# Pattern - specific variable values

   %
   .c:
   # makefile(from `Makefile', line 1)
# YYLEXFLAG := -d
# variable set hash-table stats:
# Load=1/16=6%, Rehash=0, Collisions=0/1=0%

%.h :
# makefile (from `
      Makefile ', line 1)
      # YYLEXFLAG: = -d # variable set hash - table stats:
      # Load = 1 / 16 = 6 % , Rehash = 0, Collisions = 0 / 1 = 0 %

      # 2 pattern - specific variable values
# Not a target:
   .p.o:
   # Implicit rule search has not been done.
# Modification time never checked.
# File has not been updated.
# commands to execute(built - in ):
   $(COMPILE.p) $(OUTPUT_OPTION) $ <

   lib / ui / libui.a: lib / ui / ui.o
# Implicit rule search has not been done.
# Last modified 2004 - 04 - 01 22: 04: 09.515625
# File has been updated.
# Successfully updated.
# commands to execute(from `../mp3_player/lib/ui/module.mk', line 3):
        ar rv $@ $^

lib/codec/codec.o: ../mp3_player/lib/codec/codec.c ../mp3_player/lib/codec/codec.c ..
/mp3_player/include/codec/codec.h
#  Implicit rule search has been done.
#  Implicit/static pattern stem: `
      lib / codec / codec '
      # Last modified 2004 - 04 - 01 22: 04: 08.40625 # File has been updated.# Successfully updated.# commands to execute(built - in ):
      $(COMPILE.c) $(OUTPUT_OPTION) $ <
$ make--warn - undefined - variables - n
makefile: 35: warning: undefined variable MAKECMDGOALS
makefile: 45: warning: undefined variable CFLAGS
makefile: 45: warning: undefined variable TARGET_ARCH
   ...
   makefile: 35: warning: undefined variable MAKECMDGOALS
make: warning: undefined variable CFLAGS
make: warning: undefined variable TARGET_ARCH
make: warning: undefined variable CFLAGS
make: warning: undefined variable TARGET_ARCH
   ...
   make: warning: undefined variable LDFLAGS
make: warning: undefined variable TARGET_ARCH
make: warning: undefined variable LOADLIBES
make: warning: undefined variable LDLIBS
File all does not exist.
File app / player / play_mp3 does not exist.
File app / player / play_mp3.o does not exist.
Must remake target app / player / play_mp3.o.
gcc..... / mp3_player / app / player / play_mp3.c
Successfully remade target file app / player / play_mp3.o.
File all does not exist.
Considering target file app / player / play_mp3.
File app / player / play_mp3 does not exist.
Considering target file app / player / play_mp3.o.
File app / player / play_mp3.o does not exist.
Pruning file.. / mp3_player / app / player / play_mp3.c.
Pruning file.. / mp3_player / app / player / play_mp3.c.
Pruning file.. / mp3_player / include / player / play_mp3.h.
Finished prerequisites of target file app / player / play_mp3.o.
Must remake target app / player / play_mp3.o.
gcc..... / mp3_player / app / player / play_mp3.c
Successfully remade target file app / player / play_mp3.o.
Pruning file app / player / play_mp3.o.
File all does not exist.
File app / player / play_mp3 does not exist.
Looking
for an implicit rule
for app / player / play_mp3.
Trying pattern rule with stem play_mp3.
Trying implicit prerequisite app / player / play_mp3.o.
Found an implicit rule
for app / player / play_mp3.
File app / player / play_mp3.o does not exist.
Looking
for an implicit rule
for app / player / play_mp3.o.
Trying pattern rule with stem play_mp3.
Trying implicit prerequisite app / player / play_mp3.c.
Found prerequisite app / player / play_mp3.c as VPATH.. / mp3_player / app / player /
   play_mp3.c
Found an implicit rule
for app / player / play_mp3.o.
Must remake target app / player / play_mp3.o.
gcc..... / mp3_player / app / player / play_mp3.c
Successfully remade target file app / player / play_mp3.o.
Got a SIGCHLD;
1 unreaped children.
gcc..... / mp3_player / app / player / play_mp3.c
Putting child 0x10033800(app / player / play_mp3.o) PID 576 on the chain.
Live child 0x10033800(app / player / play_mp3.o) PID 576
Got a SIGCHLD;
1 unreaped children.
Reaping winning child 0x10033800 PID 576
Removing child 0x10033800 PID 576 from chain.
load more v
75%

Put these commands in a shell script that will generate comprehensible output.,Redirection for the current command is processed from left to right.,When shell built-in commands encounter redirection errors, this will not cause the shell to exit.,Just like people know different languages and dialects, your UNIX system will usually offer a variety of shell types:

* Copyright(c) 2002 - 2007, Machtelt Garrels *
   All rights reserved.*Redistribution and use in source and binary forms, with or without *
   modification, are permitted provided that the following conditions are met:
   *
   *
   * Redistributions of source code must retain the above copyright *
   notice, this list of conditions and the following disclaimer.* * Redistributions in binary form must reproduce the above copyright *
   notice, this list of conditions and the following disclaimer in the *
   documentation and / or other materials provided with the distribution.* * Neither the name of the author, Machtelt Garrels, nor the *
   names of its contributors may be used to endorse or promote products *
   derived from this software without specific prior written permission.*
   *
   THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS"
AND ANY
   *
   EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE *
   DISCLAIMED.IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS BE LIABLE FOR ANY *
   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND *
   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
load more v
40%

If you type > or $ yourself, it is an instruction from you that the shell should redirect output or get the value of a variable.,Here we see > being used as a shell prompt, whereas > is also used to redirect output. Similarly, $ is used as a shell prompt, but, as we saw earlier, it is also used to ask the shell to get the value of a variable.,It turns out that cd without an argument will return you to your home directory, which is great if you’ve gotten lost in your own filesystem.,Depending on your default options, the shell might also use colors to indicate whether each entry is a file or directory.

$
load more v
22%

Basic bash scripting with variables and control flows,Storing the output of execution with sub shells,The idea behind a subshell is that you can store the result of the computation, as outputted to stdout to a variable:,In a bash script, by default, the script exits with the same exit status as the prior exit status. However, you can set the exit status explicitly in cases of errors using the exit command:

echo "ERROR: Something bad happened"
1 > & 2 # < --redirect file descriptor 1 to 2
load more v

Other "undefined-undefined" queries related to ""Command not found" piping a variable to cut when output stored in a variable [duplicate]"