Error command echo

Всем добрый день! Сегодня Hive OS перестал загружаться - сразу после начала загрузки виснет на сером экране. Попробовал запустить в recovery mode пишет ошибку “can`t find comand ‘echo’”. Подскажите в какую сторону копать. Переустановил биос, сам хайв на флешке - никаких изменений. Заранее спасибо

  • #1

Всем добрый день!
Сегодня Hive OS перестал загружаться — сразу после начала загрузки виснет на сером экране. Попробовал запустить в recovery mode пишет ошибку “can`t find comand ‘echo’”.
Подскажите в какую сторону копать. Переустановил биос, сам хайв на флешке — никаких изменений.
Заранее спасибо

  • #2

Перезапиши образ.
И ручками запускай. Адвансед чето там

  • #3

Перезапиши образ.
И ручками запускай. Адвансед чето там

Пробовал. Результат тот же(

  • #6

Я бы тоже сперва флэшку проверил может ей кирдык

  • #7

“can`t find comand ‘echo’”.

Ехнуть хочет, а не может!

  • #8

Ехнуть хочет, а не может!

Раз хочет, а не может — это импотенция…

  • #9

Если ты писал как рекомендуют через Балену этчер то она потом тест записаного делает. Если хэш совпадает значит все гуд и флешка не причем.

  • #10

Если ты писал как рекомендуют через Балену этчер то она потом тест записаного делает. Если хэш совпадает значит все гуд и флешка не причем.

Да через Балену делал. Попробовал другую флешку, образ — результат такой же. Больше того попробовал установать riveOs — начинает циклически его устанавливать(с ней не работал поэтому не знаю, что не так). Подозрения начинают падать на материнку((

  • #11

Отключи от матери все карты, кроме той, которая в х16. Биос сбрось и настрой 1 раз. Если не заведётся со свеженарезанным образом — ставишь винду и смотришь на ошибки синего экрана

  • #12

Батник вставился в линукс, до слез блин )))))

по существу: после can`t find comand ‘echo должно быть где
например can`t find comand ‘echo on /boot/bla-bla line: 100
давай полный вывод

  • #13

Не надо ничего придумывать, эта ошибка следствие одной из 3х причин:
1)Криво записан (кривой) образ
2)Битая флэшка
3)Флэшка мала по обьёму (у меня тоже самое писал на 4гб флэшке — на 16 всё пошло)
Скорее всего у вас просто сдохла флэшка со временем (не забывайте отключать запись логов на флэш чтобы продлить ей жизнь)

  • #14

Спасибо, всем за ответы! Путем экспериментов пришло к тому, что умер процессор. Попробовал почистить контакты — не помогло(. Так что буду менять

  • #15

Не надо ничего придумывать, эта ошибка следствие одной из 3х причин:
1)Криво записан (кривой) образ
2)Битая флэшка
3)Флэшка мала по обьёму (у меня тоже самое писал на 4гб флэшке — на 16 всё пошло)
Скорее всего у вас просто сдохла флэшка со временем (не забывайте отключать запись логов на флэш чтобы продлить ей жизнь)

Подскажите, плиз, как отключить запись логов?

  • #16

Подскажите, плиз, как отключить запись логов?

Learn how to fix echo: command not found error message in this article. We will learn fixing this error message on several Linux distributions including Ubuntu and CentOS / AlmaLinux. We will also learn to resolve this problem on MacOS X

Problem

When you run echo command in linux terminal / console, you get the following error message

Solutions to echo: command not found

How To Fix echo: command not found in Ubuntu / Debian / Kali Linux / Raspbian

To fix this problem, we can install echo using the command below.

sudo apt-get -y install coreutils

This command might take some time to finish depending on your machine internet connection.

You can also use apt command to install coreutils.

sudo apt -y install coreutils

Or if you have aptitude installed you can use the following command.

sudo aptitude install coreutils

How To Fix echo: command not found in Alpine

In Alpine Linux, we can install echo using the command below.

How To Fix echo: command not found in Arch Linux

In Arch Linux, to fix this error message, we can install echo using the command below.

How To Fix echo: command not found CentOS / Alma Linux / Oracle Linux / Red Hat Enterprise Linux (RHEL)

In CentOS or other RHEL based Linux distribution, we can install echo using the command below.

How To Fix echo: command not found in Fedora

In Fedora we can use dnf command to install echo using the command below.

How To Fix echo: command not found in OS X

To fix this problem, we can install echo using the command below.

Related Articles

  • echo Command in Linux
  • Linux Command Line Tutorial
  • Coreutils
  • GNU Coreutils Website

I have developed a script, which shows me the versions of my tools with one command.

Code: link to github repo

Result Snippet:

###############################################
########## versions (alphabetically) ##########
###############################################
bash:          3.2.57(2)-release`<br>
java:          1.7.0`<br>
/export/home/zmbf8bl/.mw701/10_scripts_tools/versions/versions.sh: line 137: npm: command not found`<br>
/export/home/zmbf8bl/.mw701/10_scripts_tools/versions/versions.sh: line 146: node: command not found`<br>
zsh:           4.3.6`<br>
###############################################

The special behaviour should be, that if a tool isn’t available the script don’t print anything about it. On Windows and macOS that works, but not on Linux.
Linux prints out e.g. npm: command not found.

How can I avoid this error message and just print nothing if a tool (e.g. npm) isn’t available on my machine???

Thanks a lot!

danglingpointer's user avatar

asked Nov 30, 2017 at 9:19

m1well's user avatar

2

just replace

2>&1 

in your code with

2>/dev/null

in general,command not found error is print to stderr
and when you do version check, redirect stderr to /dev/null
then you will get only stdout infomation

answered Nov 30, 2017 at 9:52

LiQIang.Feng's user avatar

5

To check if the command exists in your $PATH, do

checkCommand () {
    if command -v "$1" >/dev/null; then
        : # OK command exists
    else
        echo >&2 "$1: no such command"
        return 1
    fi
}

if checkCommand npm; then ...

answered Nov 30, 2017 at 11:55

glenn jackman's user avatar

glenn jackmanglenn jackman

234k37 gold badges217 silver badges342 bronze badges

There are several ways to do this, you could explicitly use something like the type command, if you knew the full path you could test if the file exists and you have execute access (-x), or you could just use an if:

#!/bin/bash

if ! npm arg1 arg2
   if (( ? != 127 ))
   then
      echo "npm failed $?"
   fi
fi

Bash returns 127 if the command is not found.

EDIT: You will still get the command not found error message, but it won’t stop your program. The problem with ignoring all error messages is that if the program runs but fails in some other way you will loose the error messages and you won’t know why it didn’t work.

answered Nov 30, 2017 at 9:31

cdarke's user avatar

cdarkecdarke

41.9k8 gold badges79 silver badges83 bronze badges

I want to overwrite /etc/postfix/master.cf with my own content. I’m using echo "<content>" > /etc/postfix/master.cf to try and accomplish this.

But when I do:

echo "#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: 'man 5 master').
#
# Do not forget to execute 'postfix reload' after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       -       -       -       smtpd
#smtp      inet  n       -       -       -       1       postscreen
#smtpd     pass  -       -       -       -       -       smtpd
#dnsblog   unix  -       -       -       -       0       dnsblog
#tlsproxy  unix  -       -       -       -       0       tlsproxy
submission inet n       -       -       -       -       smtpd
  -o content_filter=spamassassin
  -o syslog_name=postfix/submission
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#smtps     inet  n       -       -       -       -       smtpd
#  -o syslog_name=postfix/smtps
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       -       -       -       qmqpd
pickup    fifo  n       -       -       60      1       pickup
cleanup   unix  n       -       -       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
#qmgr     fifo  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       -       1000?   1       tlsmgr
rewrite   unix  -       -       -       -       -       trivial-rewrite
bounce    unix  -       -       -       -       0       bounce
defer     unix  -       -       -       -       0       bounce
trace     unix  -       -       -       -       0       bounce
verify    unix  -       -       -       -       1       verify
flush     unix  n       -       -       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       -       -       -       smtp
relay     unix  -       -       -       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       -       -       -       showq
error     unix  -       -       -       -       -       error
retry     unix  -       -       -       -       -       error
discard   unix  -       -       -       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       -       -       -       lmtp
anvil     unix  -       -       -       -       1       anvil
scache    unix  -       -       -       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing 'lmtp' master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd='lmtpd -a' listen='localhost:lmtp' proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -       n       n       -       2       pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
# SpamAssasin
spamassassin unix -     n       n       -       -       pipe
        user=spamd argv=/usr/bin/spamc -f -e
        /usr/sbin/sendmail -oi -f ${sender} ${recipient}" > /etc/postfix/master.cf

I get a lot of errors:

echo "#
> # Postfix master process configuration file.  For details on the format
> # of the file, see the master(5) manual page (command: 'man 5 master').
> #
> # Do not forget to execute 'postfix reload' after editing this file.
> #
> # ==========================================================================
> # service type  private unpriv  chroot  wakeup  maxproc command + args
> #               (yes)   (yes)   (yes)   (never) (100)
> # ==========================================================================
> smtp      inet  n       -       -       -       -       smtpd
> #smtp      inet  n       -       -       -       1       postscreen
> #smtpd     pass  -       -       -       -       -       smtpd
 configuration details.
> configuration details.
#
> #
uucp      unix  -       n       n       -       -       pipe
> uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
>   flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
-bash: !rmail: event not found
> #
# Other external delivery methods.
> # Other external delivery methods.
#
> #
ifmail    unix  -       n       n       -       -       pipe
> ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop (>   flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop (=yes
ipient)
> pient)
bsmtp     unix  -       n       n       -       -       pipe
> bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
>   flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -       n       n       -       2       pipe
> scalemail-backend unix  -       n       n       -       2       pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
>   flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
> mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
>   flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
>   ${nexthop} ${user}
# SpamAssasin
> # SpamAssasin
spamassassin unix -     n       n       -       -       pipe
> spamassassin unix -     n       n       -       -       pipe
        user=spamd argv=/usr/bin/spamc -f -e
>         user=spamd argv=/usr/bin/spamc -f -e
        /usr/sbin/sendmail -oi -f ${sender} ${recipient}" > /etc/postfix/master.cf>         /usr/sbin/sendmail -oi -f ${sender} ${recipient}" > /etc/postfix/master.cf  1       oqmgr
root@<redacted>-1:~# tlsmgr    unix  -       -       -       1000?   1       tlsmgr
tlsmgr: command not found
root@<redacted>-1:~# rewrite   unix  -       -       -       -       -       trivial-rewrite
No command 'rewrite' found, did you mean:
 Command 'rewriter' from package 'ladr4-apps' (universe)
rewrite: command not found
root@<redacted>-1:~# bounce    unix  -       -       -       -       0       bounce
No command 'bounce' found, did you mean:
 Command 'kbounce' from package 'kbounce' (main)
 Command 'bounced' from package 'sympa' (universe)
 Command 'bouncy' from package 'bouncy' (universe)
bounce: command not found
root@<redacted>-1:~# defer     unix  -       -       -       -       0       bounce
No command 'defer' found, did you mean:
 Command 'refer' from package 'groff' (main)
defer: command not found
root@<redacted>-1:~# trace     unix  -       -       -       -       0       bounce
No command 'trace' found, did you mean:
 Command 'btrace' from package 'blktrace' (universe)
 Command 'itrace' from package 'irpas' (multiverse)
 Command 'ltrace' from package 'ltrace' (main)
 Command 'mtrace' from package 'libc-dev-bin' (main)
 Command 'tracer' from package 'pvm-dev' (universe)
 Command 'grace' from package 'grace' (universe)
 Command 'xtrace' from package 'xtrace' (universe)
 Command 'tracd' from package 'trac' (universe)
 Command 'strace' from package 'strace' (main)
 Command 'dtrace' from package 'systemtap-sdt-dev' (universe)
 Command 'rtrace' from package 'radiance' (universe)
trace: command not found
root@<redacted>-1:~# verify    unix  -       -       -       -       1       verify
The program 'verify' is currently not installed.  You can install it by typing:
apt-get install argyll
root@<redacted>-1:~# flush     unix  n       -       -       1000?   0       flush
The program 'flush' is currently not installed.  You can install it by typing:
apt-get install flush
root@<redacted>-1:~# proxymap  unix  -       -       n       -       -       proxymap
proxymap: command not found
root@<redacted>-1:~# proxywrite unix -       -       n       -       1       proxymap
proxywrite: command not found
root@<redacted>-1:~# smtp      unix  -       -       -       -       -       smtp
The program 'smtp' is currently not installed.  You can install it by typing:
apt-get install apcupsd
root@<redacted>-1:~# relay     unix  -       -       -       -       -       smtp
No command 'relay' found, did you mean:
 Command 'rplay' from package 'rplay-client' (universe)
relay: command not found
root@<redacted>-1:~# #       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
root@<redacted>-1:~# showq     unix  n       -       -       -       -       showq
The program 'showq' is currently not installed.  You can install it by typing:
apt-get install showq
root@<redacted>-1:~# error     unix  -       -       -       -       -       error
No command 'error' found, did you mean:
 Command 'perror' from package 'mysql-server-5.5' (main)
error: command not found
root@<redacted>-1:~# retry     unix  -       -       -       -       -       error
No command 'retry' found, did you mean:
 Command 'retrv' from package 'atfs' (universe)
retry: command not found
root@<redacted>-1:~# discard   unix  -       -       -       -       -       discard
discard: command not found
root@<redacted>-1:~# local     unix  -       n       n       -       -       local
-bash: local: can only be used in a function
root@<redacted>-1:~# virtual   unix  -       n       n       -       -       virtual
No command 'virtual' found, did you mean:
 Command 'virtaal' from package 'virtaal' (universe)
virtual: command not found
root@<redacted>-1:~# lmtp      unix  -       -       -       -       -       lmtp
No command 'lmtp' found, did you mean:
 Command 'lftp' from package 'lftp' (main)
 Command 'smtp' from package 'apcupsd' (universe)
 Command 'gmtp' from package 'gmtp' (universe)
 Command 'ldtp' from package 'ldtp' (universe)
 Command 'mtp' from package 'ferret-vis' (universe)
lmtp: command not found
root@<redacted>-1:~# anvil     unix  -       -       -       -       1       anvil
anvil: command not found
root@<redacted>-1:~# scache    unix  -       -       -       -       1       scache
No command 'scache' found, did you mean:
 Command 'ccache' from package 'ccache' (main)
scache: command not found
root@<redacted>-1:~# #
root@<redacted>-1:~# # ====================================================================
root@<redacted>-1:~# # Interfaces to non-Postfix software. Be sure to examine the manual
root@<redacted>-1:~# # pages of the non-Postfix software to find out what options it wants.
root@<redacted>-1:~# #
root@<redacted>-1:~# # Many of the following services use the Postfix pipe(8) delivery
root@<redacted>-1:~# # agent.  See the pipe(8) man page for information about ${recipient}
root@<redacted>-1:~# # and other message envelope options.
root@<redacted>-1:~# # ====================================================================
root@<redacted>-1:~# #
root@<redacted>-1:~# # maildrop. See the Postfix MAILDROP_README file for details.
root@<redacted>-1:~# # Also specify in main.cf: maildrop_destination_recipient_limit=1
root@<redacted>-1:~# #
root@<redacted>-1:~# maildrop  unix  -       n       n       -       -       pipe
The program 'maildrop' can be found in the following packages:
 * courier-maildrop
 * maildrop
Try: apt-get install <selected package>
root@<redacted>-1:~#   flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
-d: command not found
root@<redacted>-1:~# #
root@<redacted>-1:~# # ====================================================================
root@<redacted>-1:~# #
root@<redacted>-1:~# # Recent Cyrus versions can use the existing 'lmtp' master.cf entry.
root@<redacted>-1:~# #
root@<redacted>-1:~# # Specify in cyrus.conf:
root@<redacted>-1:~# #   lmtp    cmd='lmtpd -a' listen='localhost:lmtp' proto=tcp4
root@<redacted>-1:~# #
root@<redacted>-1:~# # Specify in main.cf one or more of the following:
root@<redacted>-1:~# #  mailbox_transport = lmtp:inet:localhost
root@<redacted>-1:~# #  virtual_transport = lmtp:inet:localhost
root@<redacted>-1:~# #
root@<redacted>-1:~# # ====================================================================
root@<redacted>-1:~# #
root@<redacted>-1:~# # Cyrus 2.1.5 (Amos Gouaux)
root@<redacted>-1:~# # Also specify in main.cf: cyrus_destination_recipient_limit=1
root@<redacted>-1:~# #
root@<redacted>-1:~# #cyrus     unix  -       n       n       -       -       pipe
root@<redacted>-1:~# #  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
root@<redacted>-1:~# #
root@<redacted>-1:~# # ====================================================================
root@<redacted>-1:~# # Old example of delivery via Cyrus.
root@<redacted>-1:~# #
root@<redacted>-1:~# #old-cyrus unix  -       n       n       -       -       pipe
root@<redacted>-1:~# #  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
root@<redacted>-1:~# #
root@<redacted>-1:~# # ====================================================================
root@<redacted>-1:~# #
root@<redacted>-1:~# # See the Postfix UUCP_README file for configuration details.
root@<redacted>-1:~# #
root@<redacted>-1:~# uucp      unix  -       n       n       -       -       pipe
The program 'uucp' is currently not installed.  You can install it by typing:
apt-get install uucp
root@<redacted>-1:~#   flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
-bash: !rmail: event not found
root@<redacted>-1:~# #
root@<redacted>-1:~# # Other external delivery methods.
root@<redacted>-1:~# #
root@<redacted>-1:~# ifmail    unix  -       n       n       -       -       pipe
ifmail: command not found
root@<redacted>-1:~#   flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
-bash: syntax error near unexpected token `('
root@<redacted>-1:~# bsmtp     unix  -       n       n       -       -       pipe
The program 'bsmtp' is currently not installed.  You can install it by typing:
apt-get install bacula-common
root@<redacted>-1:~#   flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
-t: command not found
root@<redacted>-1:~# scalemail-backend unix  -       n       n       -       2       pipe
scalemail-backend: command not found
root@<redacted>-1:~#   flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
root@<redacted>-1:~# mailman   unix  -       n       n       -       -       pipe
mailman: command not found
root@<redacted>-1:~#   flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
root@<redacted>-1:~#   ${nexthop} ${user}
No command 'list' found, did you mean:
 Command 'dist' from package 'nmh' (universe)
 Command 'lst' from package 'lustre-utils' (universe)
 Command 'slist' from package 'ncpfs' (universe)
 Command 'klist' from package 'heimdal-clients' (universe)
 Command 'klist' from package 'krb5-user' (universe)
 Command 'listg' from package 'nauty' (multiverse)
 Command 'hist' from package 'loki' (universe)
 Command 'flist' from package 'nmh' (universe)
 Command 'last' from package 'sysvinit-utils' (main)
 Command 'gist' from package 'yorick' (universe)
 Command 'bist' from package 'bist' (universe)
list: command not found
root@<redacted>-1:~# # SpamAssasin
root@<redacted>-1:~# spamassassin unix -     n       n       -       -       pipe
The program 'spamassassin' is currently not installed.  You can install it by typing:
apt-get install spamassassin
root@<redacted>-1:~#         user=spamd argv=/usr/bin/spamc -f -e
-f: command not found
root@<redacted>-1:~#         /usr/sbin/sendmail -oi -f ${sender} ${recipient}" > /etc/postfix/master.cf

What should I try next?

Написание надежного, без ошибок сценария bash всегда является сложной задачей. Даже если вы написать идеальный сценарий bash, он все равно может не сработать из-за внешних факторов, таких как некорректный ввод или проблемы с сетью.

В оболочке bash нет никакого механизма поглощения исключений, такого как конструкции try/catch. Некоторые ошибки bash могут быть молча проигнорированы, но могут иметь последствия в дальнейшем. Перехват и обработка ошибок в bash

Проверка статуса завершения команды

Всегда рекомендуется проверять статус завершения команды, так как ненулевой статус выхода обычно указывает на ошибку

if ! command; then
    echo "command returned an error"
fi

Другой (более компактный) способ инициировать обработку ошибок на основе статуса выхода — использовать OR:

<command_1> || <command_2>

С помощью оператора OR, <command_2> выполняется тогда и только тогда, когда <command_1> возвращает ненулевой статус выхода.

В качестве второй команды, можно использовать свою Bash функцию обработки ошибок

error_exit()
{
    echo "Error: $1"
    exit 1
}

bad-command || error_exit "Some error"

В Bash имеется встроенная переменная $?, которая сообщает вам статус выхода последней выполненной команды.

Когда вызывается функция bash, $? считывает статус выхода последней команды, вызванной внутри функции. Поскольку некоторые ненулевые коды выхода имеют специальные значения, вы можете обрабатывать их выборочно.

status=$?

case "$status" in
"1") echo "General error";;
"2") echo "Misuse of shell builtins";;
"126") echo "Command invoked cannot execute";;
"128") echo "Invalid argument";;
esac

Выход из сценария при ошибке в Bash

Когда возникает ошибка в сценарии bash, по умолчанию он выводит сообщение об ошибке в stderr, но продолжает выполнение в остальной части сценария. Даже если ввести неправильную команду, это не приведет к завершению работы сценария. Вы просто увидите ошибку «command not found».

Такое поведение оболочки по умолчанию может быть нежелательным для некоторых bash сценариев. Например, если скрипт содержит критический блок кода, в котором не допускаются ошибки, вы хотите, чтобы ваш скрипт немедленно завершал работу при возникновении любой ошибки внутри этого блока . Чтобы активировать это поведение «выход при ошибке» в bash, вы можете использовать команду set следующим образом.

set -e
# некоторый критический блок кода, где ошибка недопустима
set +e

Вызванная с опцией -e, команда set заставляет оболочку bash немедленно завершить работу, если любая последующая команда завершается с ненулевым статусом (вызванным состоянием ошибки). Опция +e возвращает оболочку в режим по умолчанию. set -e эквивалентна set -o errexit. Аналогично, set +e является сокращением команды set +o errexit.

set -e
true | false | true
echo "Это будет напечатано" # "false" внутри конвейера не обнаружено

Если необходимо, чтобы при любом сбое в работе конвейеров также завершался сценарий bash, необходимо добавить опцию -o pipefail.

set -o pipefail -e
true | false | true # "false" внутри конвейера определен правильно
echo "Это не будет напечатано"

Для «защиты» критический блока в сценарии от любого типов ошибок команд или ошибок конвейера, необходимо использовать следующую комбинацию команд set.

set -o pipefail -e
# некоторый критический блок кода, в котором не допускается ошибка или ошибка конвейера
set +o pipefail +e

  • Печать

Страницы: [1]   Вниз

Тема: Побил GRUB и нужна помощь  (Прочитано 5939 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн
_Karakurt_

Долгая история, но в результате я грубо прервал установку GRUB на свой основной диск. MBR успел встать, однако с модулями всё явно фигово. Изначально он не мог найти normal.mod , из-за чего я загрузился с флешки и попытался тупо переставить GRUB привычным
 sudo grub-install /dev/sda1
, однако эта затея провалилась. То /cow не хватало, то устройство не указано, в общем я не смог.
Но тут мою дурную голову пронзила гениальная мысль — тупо normal.mod, ручками. Это мне удалось, и теперь GRUB даже запускает свою менюшку и… В общем, смотрите картинки. Вторая получается при любой попытке загрузить ось.
Теперь то я уже понимаю, что это была дурная затея — пытаться тупо скопировать, но уже содеянно, и как из этого мне выбраться лично мне не ясно.
Прошу помощи!


Пользователь добавил сообщение 23 Марта 2018, 20:51:32:


Мда…
Никак не желают укладываться эти две фотографии в 400 kb. И я сильно сомневаюсь что это вообще реально.
Тогда опишу словами: менюшка GRUB нормальная, с строкой загрузки моей привычной прошивки и уже менее понятной строкой с кучей знаков вопроса. В этой строке у меня есть возможность выбрать старые версии ядер.
Вторая фотка, после попытки загрузить любую ось, просто отчёты терминала:
  error: can’t find command ‘]’.
  error: can’t find command ‘]’.
  error: can’t find command ‘save_env’.
  error: can’t find command ‘]’.
  error: file ‘/boot/grub/i386-pc/all_video’ not found.
  error: can’t find command ‘]’.
  error: can’t find command ‘]’.
  error: can’t find command ‘]’.
  error: can’t find command ‘search’.
  error: can’t find command ‘echo’.
  error: can’t find command ‘linux’.
  error: can’t find command ‘echo’.
  error: can’t find command ‘initrd’.

  Press any key to continue_

« Последнее редактирование: 23 Марта 2018, 20:53:18 от _Karakurt_ »


Оффлайн
Heider

sudo grub-install /dev/sda1

Единица здесь лишняя.


Оффлайн
andytux

…попытался тупо переставить GRUB привычным
 sudo grub-install /dev/sda1

В общем случае груб устанавливается так:

Пояснения.
/dev/sdb — сюда установится первая часть груб, в данном случае MBR.
sdb1 — корневой раздел установленной Ubuntu, здесь будет создан каталог /boot/grub и здесь груб будет искать свои файлы.
Проверьте, сохранился файл /boot/grub/grub.cfg или нет.
Если нет, то придется скопировать или создать.

« Последнее редактирование: 24 Марта 2018, 10:41:40 от andytux »


Оффлайн
_Karakurt_

Я пробовал и так и так, ответ был одинаковый. Сейчас не могу сказать какой, вечером скажу точно. Вроде ругался на то, что устройство не указано, но я не уверен.


Пользователь добавил сообщение 24 Марта 2018, 10:26:45:


Проверьте, сохранился файл /boot/grub/grub.cfg

Файл сохранился


Оффлайн
Heider

ругался на то, что устройство не указано

Вы пробовали запускать нормальную команду?

sudo grub-install /dev/sdaБез единицы!!!

Вы своей командой: sudo grub-install /dev/sda1 указали установщику не устройство, а раздел.


Оффлайн
_Karakurt_

Да, я запускал и без неё и с нею, ответ одинаковый:
  grub-probе: error: failed to get canonical path of’/cow’
Через строчку то же самое, но уже от grub-install.real


Пользователь добавил сообщение 24 Марта 2018, 21:20:34:


Если попытаться поставить только модули:
Первая строчка такая же, вторая — нормальное «Installing for i386-pc platform» , а вот третья то, что я говорил:
 grub-install.real: error: install device isn’t specified


Пользователь добавил сообщение 24 Марта 2018, 21:26:54:


« Последнее редактирование: 24 Марта 2018, 21:38:26 от _Karakurt_ »


Оффлайн
archuser

_Karakurt_, из liveCD измените корневой каталог:

sudo mount /dev/sdX1 /mnt
sudo mount -t proc /proc /mnt/proc
sudo mount --rbind /dev /mnt/dev
sudo mount --rbind /sys /mnt/sys
sudo mount -o bind /run /mnt/run
sudo chroot /mnt
где sdX1 замените на соответствующий корню. И именно с этого места установите grub, как уже выше советовали.


Оффлайн
_Karakurt_

mount /dev/sdb1 /mnt/sdb1
grub-install —root-directory=/mnt/sdb1 /dev/sdb

Сделал я это, комп снова ругнулся по поводу /cow но написал что установка успешная, проблем нет.
Я радостно завершаю работу,отключаю комп, вытаскиваю флешку, включаю и…
GRUB без менюшки, командная строка. Однако теперь она поддерживает куда больше команд, чем в grub rescue. Вроде похоже на прогресс, но дальше что?
Вот это выполнил:
set prefix=(hd0,1)/boot/grub
set root=(hd0,1)
insmod ext2
insmod normal
normal
Но меню, как ожидалось, не появилось. Даже ошибок не было. Просто выполнилось и потребовало новой команды.


Пользователь добавил сообщение 24 Марта 2018, 22:46:59:


Код: [Выделить]

sudo mount /dev/sdX1 /mnt
sudo mount -t proc /proc /mnt/proc
sudo mount —rbind /dev /mnt/dev
sudo mount —rbind /sys /mnt/sys
sudo mount -o bind /run /mnt/run
sudo chroot /mnt

где sdX1 замените на соответствующий корню. И именно с этого места установите grub, как уже выше советовали.

А вот это сработало на все 100! Спасибо!
 Только бы ещё понять почему потребовалось всё перемонтрировать…
 И да, надо ли теперь выполнять уже из правильной прошивки » sudo grub-install /dev/sda» или уже всё в порядке?

« Последнее редактирование: 24 Марта 2018, 22:46:59 от _Karakurt_ »


Оффлайн
andytux

А вот это сработало на все 100! Спасибо!
 Только бы ещё понять почему потребовалось всё перемонтрировать…

Потому что вы пошли по сложному варианту — установка груб через croot (5 монтирований).
И установка файлов груб только на раздел, который «зачрутили».
В то время как в этом варианте:

mount /dev/sdb1 /mnt/sdb1
grub-install —root-directory=/mnt/sdb1 /dev/sdb

только одно монтирование и полная свобода в выборе места установки и головной части и файлов груб.

И да, надо ли теперь выполнять уже из правильной прошивки » sudo grub-install /dev/sda» или уже всё в порядке?

Нет, не надо.


Оффлайн
_Karakurt_


  • Печать

Страницы: [1]   Вверх

I want to run a script on a machine accessible only via minicom. I tried this:

echo 'echo test' >> s.sh
sudo minicom -S s.sh -D /dev/ttyUSB0

A shell does open, but starts with this error: script "s.sh" line 1: unknown command "echo".

If I type echo test in the shell that just opened, it works:

user@machine:~$ echo test
test

No other command I tried to put in s.sh was recognized (ls, ifconfig…), even though they can be launched from the shell. Why can’t they be launched from the script?

asked Jul 11, 2019 at 11:19

Hey's user avatar

4

As @steeldriver mentioned, minicom doesn’t seem to accept shell scripts. According to this man page, we can run a shell command by writing it after !.

I replaced my script’s content with

! echo test

…and the command sudo minicom -S s.sh -D /dev/ttyUSB0 works.

answered Jul 11, 2019 at 12:05

Hey's user avatar

HeyHey

6418 silver badges20 bronze badges

You need to add shebang at the top of the script #!/bin/bash or #!/bin/sh or whatever your shell is.

#!/bin/bash
echo test

answered Jul 11, 2019 at 11:37

Vignesh SP's user avatar

Vignesh SPVignesh SP

2881 silver badge11 bronze badges

3

/bin/sh: @echo: command not found

If you get this one, remember about missing new line after shell call that spans over multiple lines that are split with . You will get this error in case you don’t add explicit new line and you want to silence the command using @ symbol at the same time.

LIST=a b c d

all:
        @echo "Starting!"
        @echo "Loop over values"

        @for target in `echo ${LIST}`; do 
                echo "Value: $$target"; 
        done; 
        @echo "Done!"

Below, you have new line after last – this one will work without any problems.

LIST=a b c d

all:
        @echo "Starting!"
        @echo "Loop over values"

        @for target in `echo ${LIST}`; do 
                echo "Value: $$target"; 
        done; 

        @echo "Done!"

Alternatively, you can make last echo to be part of the multiline command. Here, you will get the expected result as well.

LIST=a b c d

all:
        @echo "Starting!"
        @echo "Loop over values"

        @for target in `echo ${LIST}`; do 
                echo "Value: $$target"; 
        done; 
        echo "Done!"

Whether to use this approach or not (I mean, to call shell from Makefile) is the topic for a completely different story.

More about commands modifiers: here

April 5th, 2017 in
main entries

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error comma colon decorator or end of line expected after operand
  • Error combo little inferno
  • Error com epicgames fortnite invalid parameter
  • Error column specified more than once
  • Error column reference title is ambiguous

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии