source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
234,213
I was looking up how to install java on Debian properly. Came to Debian wiki (that's one thing I really appreciate on Debian, the wiki's great), and this is the tip I got there: Just run aptitude search "?provides(java-runtime)" on your system to list available packages). So I thought this ?provides is some query in description, but behold: i A default-jre - Standard Java or Java compatible Runtime p default-jre:i386 - Standard Java or Java compatible Runtime i A default-jre-headless - Standard Java or Java compatible Runtime (headless) p default-jre-headless:i386 - Standard Java or Java compatible Runtime (headless) p gcj-4.8-jre - Java runtime environment using GIJ/Classpath p gcj-4.8-jre:i386 - Java runtime environment using GIJ/Classpath p gcj-4.8-jre-headless - Java runtime environment using GIJ/Classpath (headless version) p gcj-4.8-jre-headless:i386 - Java runtime environment using GIJ/Classpath (headless version) p gcj-4.9-jre - Java runtime environment using GIJ/Classpath p gcj-4.9-jre:i386 - Java runtime environment using GIJ/Classpath p gcj-4.9-jre-headless - Java runtime environment using GIJ/Classpath (headless version) p gcj-4.9-jre-headless:i386 - Java runtime environment using GIJ/Classpath (headless version) p gcj-jre - Java runtime environment using GIJ/Classpath p gcj-jre:i386 - Java runtime environment using GIJ/Classpath p gcj-jre-headless - Java runtime environment using GIJ/Classpath (headless version) p gcj-jre-headless:i386 - Java runtime environment using GIJ/Classpath (headless version) i A openjdk-7-jre - OpenJDK Java runtime, using Hotspot JIT p openjdk-7-jre:i386 - OpenJDK Java runtime, using Hotspot JIT i A openjdk-7-jre-headless - OpenJDK Java runtime, using Hotspot JIT (headless) p openjdk-7-jre-headless:i386 - OpenJDK Java runtime, using Hotspot JIT (headless) The string java-runtime does not ever occur in output, which suggests there are hidden properties being queried. Which are these?
Each package has different fields. You see the package nameand the short description listed, but query the Provides -field. You can list all fields of all the available versions of a package with $ apt-cache show openjdk-7-jre and get (shortened, depending on your system:) [...]Package: openjdk-7-jreSource: openjdk-7Version: 7u3-2.1.7-1[...]Architecture: amd64Provides: java-runtime, java2-runtime, java5-runtime, java6-runtime, java7-runtimeDepends: openjdk-7-jre-headless (= 7u3-2.1.7-1), libasound2 (>= 1.0.16), libatk1.0-0 (>= 1.12.4), libc6 (>= 2.11), libcairo2 (>= 1.2.4), libcups2 (>= 1.4.0), libfontconfig1 (>= 2.9.0), libfreetype6 (>= 2.2.1), libgdk-pixbuf2.0-0 (>= 2.22.0), libgif4 (>= 4.1.4), libglib2.0-0 (>= 2.16.0), libgtk2.0-0 (>= 2.8.0), libjpeg8 (>= 8c), libpango1.0-0 (>= 1.14.0), libpng12-0 (>= 1.2.13-4), libpulse0 (>= 0.99.1), libx11-6, libxext6, libxi6, libxrender1, libxtst6, zlib1g (>= 1:1.1.4), libxrandr2, libxinerama1, libgl1-mesa-glx | libgl1, libatk-wrapper-java-jni (>= 0.30.4-0ubuntu2)Recommends: libgnome2-0, libgnomevfs2-0, libgconf2-4, ttf-dejavu-extraSuggests: icedtea-7-pluginConflicts: icedtea-gcjwebplugin (<< 1.0-1ubuntu4)Description-en: OpenJDK Java runtime, using Hotspot JIT Full Java runtime environment - needed for executing Java GUI and Webstart programs. Using Hotspot JIT. The packages are built using the IcedTea build support and patches from the IcedTea project.[...] About the listed files: :i386 means the package is for the i386 architecture (not amd64 which you are probably using) headless means for systems without graphical display (less dependencies) gcj is the java runtime from the gcc project openjdk is the more official free implementation of java which you probably want to use See also https://askubuntu.com/questions/377750/what-is-the-difference-between-default-jdk-ecj-gcj-and-openjdk
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234213", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/27719/" ] }
234,240
I noticed there's default tilde + alias exist: [root@xiaobai ~]# cd ~[press Tab]~abrt/ ~dbus/ ~lp/ ~openvpn/ ~root/ ~systemd-network/~adm/ ~ftp/ ~mail/ ~operator/ ~rpc/ ~systemd-resolve/~apache/ ~games/ ~mpd/ ~pkg-build/ ~rpcuser/ ~systemd-timesync/~avahi/ ~gdm/ ~mysql/ ~polkitd/ ~rtkit/ ~tcpdump/~avahi-autoipd ~geoclue/ ~nfs4user/ ~postfix/ ~saslauth/ ~toranon/~bin/ ~gnome-initial-setup ~nfsnobody/ ~postgres/ ~shutdown/ ~tss~chrony/ ~halt/ ~nm-openconnect/ ~pulse ~sshd/ ~unbound/~colord/ ~iguanair/ ~nobody/ ~qemu/ ~sync/ ~usbmuxd/~daemon/ ~ldap/ ~ntop/ ~radvd/ ~systemd-bus-proxy/ ~xiaobai/[root@xiaobai ~]# cd ~halt[root@xiaobai sbin]# pwd/sbin[root@xiaobai sbin]# l ~halt14 lrwxrwxrwx. 1 root root 8 Nov 18 2014 /sbin -> usr/sbin[root@xiaobai sbin]# cd ~nobody/[root@xiaobai //]# pwd//[root@xiaobai //]# [root@xiaobai //]# realpath ~nobody//[root@xiaobai //]# Where can i set this tilde+alias (i'm not talking about ~/.bashrc) ? Any reference/documentation about this combination ? My platform is Fedora 21.
It's called tilde , not 'tidle'. They're not aliases, they're usernames on the system, when you press tab the shell is offering to auto-complete ~ to one of the user's home directories for you.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234240", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/64403/" ] }
234,253
How do I delete the last n lines of an ascii file using shell commands?
With head (removes the last 2 lines): head -n -2 file With sed / tac (removes the last 2 lines): tac file | sed "1,2d" | tac tac reverses the file, sed deletes ( d ) the lines 1 to 2 ( 2 can be any number).
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234253", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137256/" ] }
234,263
I'm not even sure whether grep is meant to be used for regex in one-line data. Googling led me to this lookahead expression that, along with grep , matches any .ext file and returns bare name: XX@XX:/$ echo name.ext | grep -oP [^\.]+(?=.ext)name That's nice, but now I prompt user for saving a file and I'm not sure whether he'll type the name with the extension or not. I tried making the lookahead conditional, ensuring all names are matched, but that returns something I don't understand: XX@XX:/$ echo name.ext | grep -oP "[^\.]+(?=.ext)?"nameext It works if I ommit the extension though: XX@XX:/$ echo name | grep -oP "[^\.]+(?=.ext)?"name So is this a grep problem or regex problem? Maybe I need to somehow make the lookahead non capturing?
You can use POSIX shell substitution to remove the .ext : file='name.ext'printf '%s\n' "${file%.ext}" To assign the extention free string to a new variable, do noext="${file%.ext}"
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234263", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/27719/" ] }
234,264
I am trying to use a variable consisting of different strings separated with a | as a case statement test. For example: string="\"foo\"|\"bar\""read choicecase $choice in $string) echo "You chose $choice";; *) echo "Bad choice!";;esac I want to be able to type foo or bar and execute the first part of the case statement. However, both foo and bar take me to the second: $ foo.shfooBad choice!$ foo.shbarBad choice! Using "$string" instead of $string makes no difference. Neither does using string="foo|bar" . I know I can do it this way: case $choice in "foo"|"bar") echo "You chose $choice";; *) echo "Bad choice!";;esac I can think of various workarounds but I would like to know if it's possible to use a variable as a case condition in bash. Is it possible and, if so, how?
The bash manual states: case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac Each pattern examined is expanded using tilde expansion, parameter and variable expansion, arithmetic substitution, command substitution, and process substitution. No «Pathname expansion» Thus: a pattern is NOT expanded with «Pathname expansion». Therefore: a pattern could NOT contain "|" inside. Only: two patterns could be joined with the "|". This works: s1="foo"; s2="bar" # or even s1="*foo*"; s2="*bar*"read choicecase $choice in $s1|$s2 ) echo "Two val choice $choice"; ;; # not "$s1"|"$s2" * ) echo "A Bad choice! $choice"; ;;esac Using « Extended Globbing » However, word is matched with pattern using « Pathname Expansion » rules. And « Extended Globbing » here , here and, here allows the use of alternating ("|") patterns. This also work: shopt -s extglobstring='@(foo|bar)'read choice case $choice in $string ) printf 'String choice %-20s' "$choice"; ;;& $s1|$s2 ) printf 'Two val choice %-20s' "$choice"; ;; *) printf 'A Bad choice! %-20s' "$choice"; ;; esacecho String content The next test script shows that the pattern that match all lines that contain either foo or bar anywhere is '*$(foo|bar)*' or the two variables $s1=*foo* and $s2=*bar* Testing script: shopt -s extglob # comment out this line to test unset extglob.shopt -p extglobs1="*foo*"; s2="*bar*"string="*foo*"string="*foo*|*bar*"string='@(*foo*|*bar)'string='*@(foo|bar)*'printf "%s\n" "$string"while IFS= read -r choice; do case $choice in "$s1"|"$s2" ) printf 'A first choice %-20s' "$choice"; ;;& $string ) printf 'String choice %-20s' "$choice"; ;;& $s1|$s2 ) printf 'Two val choice %-20s' "$choice"; ;; *) printf 'A Bad choice! %-20s' "$choice"; ;; esac echodone <<-\_several_strings_fbfoobar*foo**foo*|*bar*\"foo\""foo"afoolineonebarvaluenow foo with spaces_several_strings_
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/234264", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/22222/" ] }
234,278
I get permission denied when trying to move folder Music via mv although directory owner is set to my user and user permissions are set to 7. What's going on? (I know that I could use sudo but I want to find out what's wrong. Something smells fishy here). Ps: I am on Mac OS X El Capitan.
I was using Windows Subsystem for Linux. I had the directory open in a different bash instance. Closing it let me move the directory.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/234278", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137269/" ] }
234,311
Following all the instructions from UNIXMEN , installed postgresql-9.4 in CentOS 6.4 . Everything went well, started the service and could access pgsql screen. But when I try to configure the phpPgAdmin , I couldn't find the files postgresql.conf pg_hba.conf config.inc.php phpPgAdmin.conf The instructions says, postgresql home directory will sit in /etc/../ and some say it will be in /var/lib/ . Where does the directory gets created (in CentOS)? Is installation directory path is different in centos, redhat(RHEL7) & ubuntu? Update: I ran a quick locate command for *postgresql.conf** and *hba.conf**, I found the sample files as postgresql.conf.sample and pg_hba.conf.sample (at /usr/pgsql-9.4/share/ )
If you type the following: sudo su - postgres after installing postgresql-server, that should take you right to the home directory of postgres and will have the configuration files you are looking for. Usually in a RHEL environment, the configuration files would be stored in /var/lib/pgsql/ . On my test environment it is stored in /var/lib/pgsql/9.1/data .
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/234311", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/67557/" ] }
234,393
I would like to ssh to a machine with a pre-defined setting, specifically in zsh. To do so, I have tried doing the following from the client (inspired by this answer ): $ ssh -t machine@domain "STARTUP_OPTION='A'; exec /path/to/zsh;" and then I have the following .zshrc in the server: if [ "$STARTUP_OPTION" = "A" ]; then echo "Logging in with A"fi This doesn't seem to work. How can I login with a specific shell while passing the value for a shell variable in the remote shell?
By default the only environment variable that's transmitted over an SSH connection is TERM . You can pack information there but you've got to be sure that it'll be unpacked on the server side. The client can transmit other messages, but the server needs to be set up to accept them with an AcceptEnv directive in /etc/sshd_config . Under Debian and most derivatives (Ubuntu, Mint, …) all variables whose name begins with LC_ are also accepted by the SSH server. These variables are conventionally used for locale settings, but you can use one of your own to pass something else. If your server allows it, you can simply write LC_STARTUP_OPTION=A ssh Another possibility is to run a command based on the user authentication key (this requires only control of ~/.ssh/authorized_keys , not the sshd configuration). If you aren't able to transmit environment variables, you can set it on the command line and then execute an interactive shell, as you've been doing. Since you're executing a new shell (that's necessary because you can't both specify an initial command to run and get an interactive shell), this needs to be an environment variable, not a shell variable. ssh -t machine@domain 'export STARTUP_OPTION="A"; exec /path/to/zsh' Yet another approach is to feed some data to the shell via its standard input, and then redirect the standard input to the terminal. ssh -t localhost 'echo "echo foo; exec </dev/tty" | exec zsh -i'stdin: is not a ttystty: standard input: Inappropriate ioctl for device~% Despite the error messages about not being able to initialize the terminal, zsh seems to cope properly with the interactive part of the session.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234393", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/4531/" ] }
234,402
I was wondering if there was a way to register this, but since most modern search engines don't work well with phrases over about 5 words in length, I need some help on this one. I was wondering this because I'm making a bash script that has to register files as certain types and make decisions accordingly. This technically isn't important to my project, but I was curious. Also, if they are considered to be regular files, then is there a way to check if these files are hard linked without having to parse ls -i ? And is there a way to check if some arbitrary file, X, is hard linked to some other arbitrary file, Y, without using the find -i command?
In Unix-style systems, the data structure which represents filesystem objects (in other words, the data about a file), is stored in what's called an "inode". A file name is just a link to this inode, and is referred to as a "hard link". There is no difference between the first name a file is given and any subsequent link. So the answer is, "yes": a hard link is a regular file and, indeed, a regular file is a hard link. The ls command will show you how many hard links there are to the file. For example: seumasmac@comp:~$ echo Hello > /tmp/hello.txtseumasmac@comp:~$ ls -l /tmp/hello.txt -rw-rw-r-- 1 seumasmac seumasmac 6 Oct 4 13:05 /tmp/hello.txt Here we've created a file called /tmp/hello.txt . The 1 in the output from ls -l indicates that there is 1 hard link to this file. This hard link is the filename itself /tmp/hello.txt . If we now create another hard link to this file: seumasmac@comp:~$ ln /tmp/hello.txt /tmp/helloagain.txtseumasmac@comp:~$ ls -l /tmp/hello*-rw-rw-r-- 2 seumasmac seumasmac 6 Oct 4 13:05 /tmp/helloagain.txt-rw-rw-r-- 2 seumasmac seumasmac 6 Oct 4 13:05 /tmp/hello.txt you can now see that both filenames indicate there are 2 hard links to the file. Neither of these is the "proper" filename, they're both equally valid. We can see that they both point to the same inode (in this case, 5374043): seumasmac@comp:~$ ls -i /tmp/hello*5374043 /tmp/helloagain.txt 5374043 /tmp/hello.txt There is a common misconception that this is different for directories. I've heard people say that the number of links returned by ls for a directory is the number of subdirectories, including . and .. which is incorrect . Or, at least, while it will give you the correct number, it's right for the wrong reasons! If we create a directory and do a ls -ld we get: seumasmac@comp:~$ mkdir /tmp/testdirseumasmac@comp:~$ ls -ld /tmp/testdirdrwxrwxr-x 2 seumasmac seumasmac 4096 Oct 4 13:20 /tmp/testdir This shows there are 2 hard links to this directory. These are: /tmp/testdir/tmp/testdir/. Note that /tmp/testdir/.. is not a link to this directory, it's a link to /tmp . And this tells you why the "number of subdirectories" thing works. When we create a new subdirectory: seumasmac@comp:~$ mkdir /tmp/testdir/dir2seumasmac@comp:~$ ls -ld /tmp/testdirdrwxrwxr-x 3 seumasmac seumasmac 4096 Oct 4 13:24 /tmp/testdir you can now see there are 3 hard links to /tmp/testdir directory. These are: /tmp/testdir/tmp/testdir/./tmp/testdir/dir2/.. So every new sub-directory will increase the link count by one, because of the .. entry it contains.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/234402", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/130361/" ] }
234,412
I have the following block in my /etc/hosts : # The following lines are desirable for IPv6 capable hosts::1 localhost ip6-localhost ip6-loopbackfe00::0 ip6-localnetff00::0 ip6-mcastprefixff02::1 ip6-allnodesff02::2 ip6-allroutersff02::3 ip6-allhosts They were inserted by some automagic in Ubuntu and not written by me. I've found lots of documents that say that you should have these lines. But why? Why are they desirable? My suspicion is that they aren't and are just cruft (except for the first one). Because if you google one of the names, eg ip6-allrouters , all you find are references to /etc/hosts but no one is actually using them. Another way of phrasing this question is, what harm will come unto me or what feature will not function properly if I remove these lines? If the answer is none , can we conclude that they are redundant?
According to RFC 4291, Section 2.7: Multicast Addresses , the first 8 bits ( FF in FF0X ) at the beginning of identifies the address as a muticast address. The flags , the next 4 bits, (the first 0 in FF0X ) in the question indicate: ... a permanently-assigned ("well-known") multicast address, assignedby the Internet Assigned Numbers Authority (IANA). The next 4 bits, (the last hex value 0 or 2 in FF00 or FF02 ) define the scope : 0 reserved [...] 2 Link-Local scope [...] The reserved scope is reserved for future use. The Link-local scope means, that packages within that scope will never be routed and therefore cannot leave the subnet. So the addesses mean he following: ::1: This is the loopback address, whose IPv4-equivalent is 127.0.0.1 . fe00::0 : Can be compared to the Class E address space in IPv4, therefore it's in the reserved scope; reserved for future use. ff02::1 : The group of all IPv6 nodes (including the routers) in the Link-local scope, whose IPv4-equivalent is 224.0.0.1 . ff02::2 : The group of all IPv6 routers in the Link-local scope, whose IPv4-equivalent is 224.0.0.2 . ff02::3 : This exists no longer an is unassigned at the moment. Earlier it stood for the group of all hosts (excluding the routers) in the Link-local scope. Further reading / References : RFC 4291: IP Version 6 Addressing Architecture RFC 6890: Special-Purpose IP Address Registries RFC 7346: IPv6 Multicast Address Scopes RFC 2365: Administratively Scoped IP Multicast (see section 8) IANA: IPv4 Multicast Address Space Registry IANA: IPv6 Multicast Address Space Registry IANA: IPv6 Address Space
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234412", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/57817/" ] }
234,432
I want to delete the last column of a txt file, while I do not know what the column number is. How could I do this? Example: Input: 1223 1234 1323 ... 2222 1231233 1234 1233 ... 3444 1250000 5553 3455 ... 2334 222 And I want my output to be: 1223 1234 1323 ... 22221233 1234 1233 ... 34440000 5553 3455 ... 2334
With awk : awk 'NF{NF-=1};1' <in >out or: awk 'NF{NF--};1' <in >out or: awk 'NF{--NF};1' <in >out Although this looks like voodoo, it works. There are three parts to each of these awk commands. The first is NF , which is a precondition for the second part. NF is a variable containing the number of fields in a line. In AWK, things are true if they're not 0 or empty string "" . Hence, the second part (where NF is decremented) only happens if NF is not 0. The second part (either NF-=1 NF-- or --NF ) is just subtracting one from the NF variable. This prevent the last field from being printed, because when you change a field (removing the last field in this case), awk re-construct $0 , concatenate all fields separated by space by default. $0 didn't contain the last field anymore. The final part is 1 . It's not magical, it's just used as a expression that means true . If an awk expression evaluates to true without any associated action, awk default action is print $0 .
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/234432", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/133262/" ] }
234,509
This works fine: #!/bin/shALTER="$1"NAME="$2"for pr in $(pgrep $NAME); do elapse=$(ps -o etime= -p $pr) [ "${elapse%:*}" -gt "$ALTER" ] && echo $prdone But if I try to switch it to CShell: #!/bin/cshset ALTER = "$1"set NAME = "$2"for pr in $(pgrep $NAME); do set elapse = $(ps -o etime= -p $pr) [ "${elapse%:*}" -gt "$ALTER" ] && echo $prdone I get an Illegal variable error. Any ideas?
The first thing you should know about scripting in csh is that it is usually a very bad idea . That said, if you insist, the problems with your script are: csh doesn't support the $() construct for command substitution, use ` ` instead. csh doesn't support the for i ... do ... done syntax, use foreach i ... end instead. csh doesn't do funky string manipulation like "${elapse%:*}" . You'll have to get around it using some other tool. I don't know how to get [ to work with csh (but it's probably possible), as a workaround, use if instead. So, a working version of your script in csh would be: #!/bin/cshset ALTER = "$1" set NAME = "$2" foreach pr (`pgrep "$NAME"`) set elapse = `ps -o etime= -p "$pr" | cut -d: -f1` if ( "$elapse" > "$ALTER" ) echo "$pr"end Seriously though, don't script in csh , it will only cause you pain. Especially since all you really need is: ps -o pid=,etime= -p $(pgrep $NAME) | cut -d: -f1 | awk -vval="$ALTER" '$2>val{print $1}'
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234509", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137397/" ] }
234,552
How can I create a Wi-Fi hotspot with the command line tool nmcli and share/bridge the ethernet internet connection with the wireless access point? Furthermore, how can I start this automatically at boot? Is this possible with nmcli ?
You can create a hotspot with the following: nmcli dev wifi hotspot ifname wlp4s0 ssid test password "test1234" (where wlp4s0 is the name of your Wifi interface). Reference: https://wiki.debian.org/WiFi/HowToUse#Troubleshooting_.26_Tips_for_NetworkManager
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/234552", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/24036/" ] }
234,581
I have a mouse that will stop working randomly. The solution is easy, unplug and replug. Is there a way I can do this via the command line though? Doing via command line has a few advantages. Doesn't wear out the connector. Faster. Saves me the trouble of crawling under my desk. Most important: prevents me from accidentally unplugging something else. Plus I am curious how to do this. OS is Debian 8. Thanks!
Save the following to usbreset.c /* usbreset -- send a USB port reset to a USB device */#include <stdio.h>#include <unistd.h>#include <fcntl.h>#include <errno.h>#include <sys/ioctl.h>#include <linux/usbdevice_fs.h>int main(int argc, char **argv){ const char *filename; int fd; int rc; if (argc != 2) { fprintf(stderr, "Usage: usbreset device-filename\n"); return 1; } filename = argv[1]; fd = open(filename, O_WRONLY); if (fd < 0) { perror("Error opening output file"); return 1; } printf("Resetting USB device %s\n", filename); rc = ioctl(fd, USBDEVFS_RESET, 0); if (rc < 0) { perror("Error in ioctl"); return 1; } printf("Reset successful\n"); close(fd); return 0;} The run the following commands in terminal: Compile the program: cc usbreset.c -o usbreset Get the Bus and Device ID of the USB device you want to reset: lsusb -t Bus# 4 -Dev# 1 Vendor 0x1d6b Product 0x0001 -Dev# 3 Vendor 0x046b Product 0xff10 Make our compiled program executable: chmod +x usbreset Execute the program with sudo privilege; make necessary substitution for <Bus> and <Device> ids as found by running the lsusb command: sudo ./usbreset /dev/bus/usb/004/003Resetting USB device /dev/bus/usb/004/003Reset successful Source of above program: http://marc.info/?l=linux-usb&m=121459435621262&w=2
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234581", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/65344/" ] }
234,590
I would like to disable the ssh server for certain times of the day. I would like to do this because I recently experienced a brute force compromise via ssh . Can crontab be used to enable/disable SSH? If not, is there another way to disable ssh at certain times of the day?
Sure, just run whatever init scripts there are to stop and start ssh daemon (e.g. /etc/init.d/ssh stop and /etc/init.d/ssh start ) at appropriate times. However, I'd suggest looking into fail2ban, portknocking, disabling password authentication and using only ssh keys, and the most secure way, two factor authentication with one ti me passwords .
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/234590", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/45243/" ] }
234,614
I have a file with a list of values that end with a letter. Is there an easy way to add a space or tab before the last character of each line to separate the number from the letter? 44A 354T 1453C 77D So that the output looks like this: 44 A 354 T 1453 C 77 D
If you never have any white space after the last character and before the end of the line, use: sed 's/.$/ &/' file or perl -pe 's/.$/ $&/' file If you can have whitespace before the end of the line, use this instead: perl -pe 's/(.*)(\S)/$1 $2/' file
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234614", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137510/" ] }
234,617
The $0 shell parameter holds the name of the calling program. If you make a symbolic link named my_command in your home directory to the command /usr/local/bin/command1 and you execute it by typing ./my_command , what will be the value of $0 ? Can anyone also explain why? Thanks!
$0 doesn't hold the name of the calling program but the name of the called program. The called program is ./my_command so $0 will be ./my_command too. The fact it is a symbolic link doesn't make a difference.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234617", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/136909/" ] }
234,731
In Linux, generally we use a lot of commands and it is difficult to remember all of them. history command provides the list of commands we used previously but its limit is less. New commands are overwritten on old commands then old commands are missing. I think somewhere the log of the commands is stored in the system. Is that log available to open and read? If possible can we change the maximum size of log that it can handle? Is the output of history command depends upon the login-user?
A simple solution is to increase the number of commands saved and returned by history . If you use bash, add this line to your ~/.profile : export HISTSIZE=100000export HISTFILESIZE=999999 From man bash : HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is trun‐ cated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files. HISTSIZE The number of commands to remember in the command history (see HISTORY below). If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234731", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/95366/" ] }
234,734
In Ubuntu I used sudo update-alternatives --config x-www-browser to set the default internet browser manually. In Manjaro I get: sudo: update-alternatives: command not found I have set Firefox as the default in its settings and want it to stay so. After installing Chromium, the default browser is now Chromium, although I reconfirmed Firefox as such and in Chromnum settings it says: "Chromium cannot determine or set the default browser". How to make Firefox default browser?
For users of i3wm, in addition to editing ~/.config/mimeapps.list and ~/.i3/config , you also need to change $BROWSER from ~/.profile , set it to /usr/bin/chromium , to prevent browser sessions emerging from the terminal from opening the wrong browser.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/234734", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/-1/" ] }
234,789
During a few years, in my $HOME directory a lot of hidden filesand directories appeared. I would like to continually delete the unneeded ones. How can I find out which applications created those hidden filesand directories. How can I be sure that it's safe to remove the hidden files and directoriesand nothing important will be lost and nothing depending on them won'tstop working?
You can just temporarily displace them. cd ~mkdir .trashfind . ! -name . -prune ! -type d -atime +365 -exec \ sh -c 'touch -a -- "$@" mv -- "$@" ~/.trash ' -- {} + That will find all files in your $HOME directory - without recursing into child directories - which have not been accessed for a year. It will update the access time for all of them to right now, and then move all of them into a directory named .trash . If you encounter any problems between the time you run it and whatever time you decide to start deleting old files in ~/.trash then you can try moving some of them back and see if any of those you put in the trash were the cause.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234789", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/6215/" ] }
234,832
Is it possible for ping command in Linux(CentOS) to send 0 bytes. In windows one can define using -l argument command tried ping localhost -s 0 PING localhost (127.0.0.1) 0(28) bytes of data. 8 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 8 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 ^C --- localhost ping statistics --- 2 packets transmitted, 2 received, 0% packet loss, time 999msman ping-s packetsize Specifies the number of data bytes to be sent. The default is 56, which translates into 64 ICMP data bytes when combined with the 8 bytes of ICMP header data. Edit1: adding windows output of ping just in case some one needs it ping 127.0.0.1 -l 0Pinging 127.0.0.1 with 0 bytes of data:Reply from 127.0.0.1: bytes=0 time<1ms TTL=128Reply from 127.0.0.1: bytes=0 time<1ms TTL=128Reply from 127.0.0.1: bytes=0 time<1ms TTL=128Ping statistics for 127.0.0.1: Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0msping 127.0.0.1Pinging 127.0.0.1 with 32 bytes of data:Reply from 127.0.0.1: bytes=32 time<1ms TTL=128Reply from 127.0.0.1: bytes=32 time<1ms TTL=128Reply from 127.0.0.1: bytes=32 time<1ms TTL=128Ping statistics for 127.0.0.1: Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0ms
A ping cannot be 0 bytes on Linux, Windows or any other platform that claims to be able to send pings. At the very least the packet must contain an IP header and a non-malformed no-trick-playing ping will also include an ICMP header, which is 8 bytes long. It is possible that windows differs in how they output the bytes received. Linux tells you the size of the ICMP portion of the packet (8 bytes for the ICMP header plus any ICMP data present). Windows may instead print the number of ICMP payload data bytes so that while it tells you "0", those 8 ICMP header bytes are still there. To truly have 0 ICMP bytes that means your packet is a raw IP header and no longer an ICMP ping request. The point is, even if windows is telling you the ping packet is 0 bytes long, it isn't. The minimum size of an ICMP echo request or echo reply packet is 28 bytes: 20 byte IP header, 4 byte ICMP header, 4 byte echo request/reply header data, 0 bytes of ICMP payload data. When ping on linux prints: 8 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 Those 8 bytes are the 4 byte ICMP header and the 4 byte ICMP echo reply header data and reflect an ICMP payload data size of 0 bytes.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/234832", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/133967/" ] }
234,859
Below is my hard disk shown in gnu parted: (parted) print free Model: ATA HGST HTS541075A9 (scsi)Disk /dev/sda: 750GBSector size (logical/physical): 512B/4096BPartition Table: gptNumber Start End Size File system Name 17.4kB 1049kB 1031kB Free Space1 1049kB 538MB 537MB fat32 EFI System Partition boot2 538MB 468GB 467GB ext4 468GB 520GB 52.4GB Free Space6 520GB 527GB 6353MB linux-swap(v1)4 527GB 527GB 524MB ext45 527GB 744GB 217GB lvm3 744GB 750GB 6352MB 750GB 750GB 892kB Free Space(parted) You can see I have 52.4GB space (fourth entry). I want to create a partition in this. I know mkpart is the command for it. Its syntax is mkpart PART-TYPE [FS-TYPE] START END But my problem is I don't know what value is should give for START and END . What value should I use?
Number Start End Size File system ...................................... 468GB 520GB 52.4GB Free Space Well, as you can see Start is 468GB and End is 520GB . Now, parted defaults to MB so you'll have to specify the unit : unit GB mkpart primary ntfs 468 520 or append unit suffix to the start/end numbers: mkpart primary ext2 468GB 520GB Alternatively, you can list the values in MB with unit MB print free and then use the start/end values without any unit/suffix e.g. mkpart primary ext2 468012 520008
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/234859", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/109220/" ] }
234,863
I have a little problem in Linux with removing spaces from selected lines from my file. For example: f h t s q e g h c h tf h t r f h v f d g nq a z x s w e d c v ff h b c h t h b v h fp l k o i j u h y g tt f r d c v b h n j u and now, how should I delete spaces from lines number 2, 4 and 5? Additionally, how's it going to look for the third line?
Using awk To remove blanks from lines 2, 4, and 5: $ awk 'NR==2 || NR==4 || NR==5 {gsub(/ /,"");} 1' file f h t s q e g h c h tfhtrfhvfdgnq a z x s w e d c v ffhbchthbvhfplkoijuhygtt f r d c v b h n j u In awk, NR is the line number. The logical expression NR==2 || NR==4 || NR==5 selects the lines of interest to you. The command gsub(/ /,"") removes blanks from those lines. The condition 1 is awk's cryptic shorthand for print the line. Using sed To remove blanks from lines 2, 4, and 5: $ sed '3n; 2,5 s/ //g' file f h t s q e g h c h tfhtrfhvfdgnq a z x s w e d c v ffhbchthbvhfplkoijuhygtt f r d c v b h n j u Here, we use slightly different logic: we remove blanks for all lines from 2 to 5 except line 3. This works as follows: the expression 3n tells sed that, when it comes to line 3, print it and skip to the next line. Otherwise, the command `2,5 s/ //g tells sed to remove blanks from all lines from 2 to 5. To remove all whitespace, not just blanks awk 'NR==2 || NR==4 || NR==5 {gsub(/[[:space:]]/,"");} 1' file Or: sed '3n; 2,5 s/[[:space:]]//g' file
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/234863", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137673/" ] }
234,903
I'm trying to tunnel to a server via a bridge server. So far, I've been able to get it working from the command shell properly using the following command: ssh -A -t [email protected] ssh -A [email protected] But I've been trying to wrap this into my ~/.ssh/config file and I have troubles. I've tried: Host axp User remote_userid HostName remoteserver.com IdentityFile ~/.ssh/id_rsa.eric ProxyCommand ssh -A -t bridge_userid@bridge_userid.com ssh -A remote_userid@%h But when I do, I get the following error message from remoteserver.com and I'm not sure what is causing it: ksh: SSH-2.0-OpenSSH_6.8^M: not found I know that when I log into remoteserver.com , my shell is /usr/bin/ksh . I've tried to add path arguments to the ssh commands in the config file, but it made no difference. Any ideas what it can be?
Jakuje's answer is right, but since OpenSSH 7.3 , you can now use -J ProxyJump which is easier. See my notes: OpenSSH 7.3 or above Use ProxyJump . As explained in the manual: -J [user@]host[:port] Connect to the target host by first making an ssh connection to the jump host and then establishing a TCP forwarding to the ultimate destination from there. Multiple jump hops may be specified separated by comma characters. This is a shortcut to specify a ProxyJump configuration directive. ProxyJump ~/.ssh/config example ~/.ssh/config Host server1 Hostname server1.example.com IdentityFile ~/.ssh/id_rsaHost server2_behind_server1 Hostname server2.example.com IdentityFile ~/.ssh/id_rsa ProxyJump server1 Connect with ssh server2_behind_server1 -v Add -v for verbose output ProxyJump -J Command line example ~/.ssh/config Host server1 Hostname server1.example.com IdentityFile ~/.ssh/id_rsaHost server2 Hostname server2.example.com IdentityFile ~/.ssh/id_rsa Connect with ssh server2 -J server1 -v Or use -o ssh server2 -o 'ProxyJump server1' -v OpenSSH 5.4 or above Use ProxyCommand with -W ~/.ssh/config Host server1 Hostname server1.example.com IdentityFile ~/.ssh/id_rsaHost server2 Hostname server2.example.com IdentityFile ~/.ssh/id_rsa ProxyCommand ssh server1 -W %h:%p Connect with ssh server2 -v Or use -o ssh server2 -o 'ProxyCommand ssh server1 -W %h:%p' -v OpenSSH bellow 5.4 ~/.ssh/config Host server1 Hostname server1.example.com IdentityFile ~/.ssh/id_rsaHost server2 Hostname server2.example.com IdentityFile ~/.ssh/id_rsa ProxyCommand ssh server1 nc %h %p 2> /dev/null Connect with: ssh server2 -v Or use -o ssh server2 -o 'ProxyCommand ssh server1 nc %h %p 2> /dev/null' -v Sources -J added in OpenSSH 7.3 ssh(1): Add a ProxyJump option and corresponding -J command-line flag to allow simplified indirection through a one or more SSH bastions or "jump hosts". -W added in OpenSSH 5.4 Added a 'netcat mode' to ssh(1): "ssh -W host:port ..." This connects stdio on the client to a single port forward on the server. This allows, for example, using ssh as a ProxyCommand to route connections via intermediate servers. bz#1618
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/234903", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/28391/" ] }
234,970
I have several SSL certificates, and I would like to be notified, when a certificate has expired. My idea is to create a cronjob, which executes a simple command every day. I know that the openssl command in Linux can be used to display the certificate info of remote server, i.e.: openssl s_client -connect www.google.com:443 But I don't see the expiration date in this output. Also, I have to terminate this command with CTRL + c . How can I check the expiration of a remote certificate from a script (preferably using openssl ) and do it in "batch mode" so that it runs automatically without user interaction?
Your command would now expect a http request such as GET index.php for example. Use this instead: if true | openssl s_client -connect www.google.com:443 2>/dev/null | \ openssl x509 -noout -checkend 0; then echo "Certificate is not expired"else echo "Certificate is expired"fi true : will just give no input followed by eof, so that openssl exits after connecting. openssl ... : the command from your question 2>/dev/null : error output will be ignored. openssl x509 : activates X.509 Certificate Data Management. This will read from standard input defaultly -noout : Suppresses the whole certificate output -checkend 0 : check if the certificate is expired in the next 0 seconds
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/234970", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/43007/" ] }
235,005
I am trying to find an alternative to this command: mpstat 5 1 Even though it works as i need, but it have a delay of 5 seconds,i need something similar, but that will give me instantly the CPU usage average of last 5 seconds.
Use a butt-simple script to record it: while true; do mpstat 5 1 > tmpstat cp tmpstat laststatdone Then run the above script in the background. The last mpstat will be available immediatley in the file laststat . It will be, however, be from 0-5 seconds stale.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235005", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/30927/" ] }
235,017
Help required - in the context of shell scripting on a GNU/LINUX bash: I always use set -e . Often, I would like to grep and do not always want the script to terminate execution if grep has an exit status of 1 indicating pattern not found. Somethings I have tried to solve this problem are as follows: (Try I) If set +o pipefail and invoke grep with something like grep 'p' | wc -l then I get the desired behaviour until a future maintainer enables pipefail . Also, I like enabling pipefail so this does not work for me. (Try II) Use a sed or awk and only print lines matching pattern, then wc matched lines to test for matched pattern. I don't like this option because using sed to grep seems like a workaround for my true problem. (Try III) This one is my least favorite - something like: set +e; grep 'p'; set-e Any insight/idioms would be most appreciated - thank you.
You can put the grep in an if condition, or if you don't care about the exit status, add || true . Example: grep kills the shell $ bash$ set -e$ echo $$33913$ grep foo /etc/motd$ echo $$9233 solution 1: throw away the non-zero exit status $ bash$ set -e$ echo $$34074$ grep foo /etc/motd || true$ echo $$34074 solution 2: explicitly test the exit status $ if ! grep foo /etc/motd; then echo not found; finot found$ echo $$34074 From the bash man page discussing set -e : The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or ││ list except the command following the final && or ││ , any command in a pipeline but the last, or if the command’s return value is being inverted with ! .
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/235017", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/24113/" ] }
235,049
Is ssh abc@servername different from ssh Abc@servername ? Does the case of the username matter in Unix? My user authenticates via LDAP.
Just like hostnames and domain names, the username is not strictly a Unix thing but can and often does span a wider range of OS types. Whether they will be considered case sensitive depends then on the standard used to specify them. Hostnames and domain names are clearly case insensitive by the DNS standard (see RFC4343 ). Usernames stored on a local backend (/etc/passwd) or a Unix style one (NIS) are not case insensitive by the POSIX standard . Usernames stored in an LDAP or an Active Directory backend will follow the used attribute schema definition, uid and cn which are often storing the user name have a differing schema attributes, case insensitive for the former but case sensitive for the latter. That means both Abc and abc might match or not abc 's entry depending on the ldap server configuration. Due to this inconsistency, I would recommend to only use lowercase for both usernames and host/domain name and then avoid ssh [email protected] which is rude anyway.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235049", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137779/" ] }
235,092
I have this command: cat somefile >file1 >file2 After I executed this command I can't figure out why file1 has nothing in it. It should have the output of the first file ( somefile ), but nothing is in it. Can you explain to me why it does not copy or write my output from somefile ? ( file2 contains my output, but file1 contains nothing)
I think there's a difference between how you think shell redirection works and how it really does. You cannot redirect the output of the shell multiple times and expect it to be redirected to all the locations you've specified. Instead, it will only be redirected to the last location, which in your case is file2 . The answer by Chaos provides a decent explanation on how such I/O Redirection works. What you really want to do is: $ cat example.txt | tee file1 > file2 tee is a program that reads from the standard input and writes to multiple file descriptors. One of them is always the standard output. So we use tee to write the output to file1 and then redirect its stdout to file2 . Also, based on suggestions in the comments, this is a better way to do what you're looking for: $ tee file1 > file2 < example.txt This approach has the advantage that it redirects the stdin instead of trying to read over a pipe. This means that the shell now needs to spawn one less process. It also eliminates what is known as "Useless use of cat".
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235092", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137802/" ] }
235,100
I can't remember the trick where I could get the last command without running it: let's say I want to be be able to access the command !1255 when pressing the up arrow key and modify the command. So what's the trick to call the command, make it be shown up in the command line but not executed and afterwards accessible via the arrow key up? I tried with putting an echo, but then I have an echo before the command, I don't remember how to do it correctly.
!1255:p Will do this ! is history recall 1255 is the line number :p prints but does not execute Then you can use up-arrow to get ther previous (unexecuted) command back and you can change it as you need. I often combine this with hg ("History Grep") - my favorite alias. $ alias hg # Maybe use hgr instead if you are a Mercurial CLI user.alias hg='history | tail -200 | grep -i' This searches for text on a recent history line, regardless of case and is used this way: When I want to search for recent vi commands to edit a certain file and then I want to re-use one of them to edit the same file but with a different file extension. $ hg variables 6153 vi Variables/user-extensions.js 6176 vi Variables/user-extensions.js 6178 vi Variables/user-extensions.js 6190 vi Variables/user-extensions.js 6230 hg variables$ # Notice the difference in case with V and v is ignored$ !6190:pvi Variables/user-extensions.js $ ["up-arrow"]$ vi Variables/user-extensions.[now change .js to .html] I also define hga ("History Grep All") to search my entire history: $ alias hgaalias hga='history | grep -i' but I don't use it much because my history is (intentionally) very large and I get too much output that later affects scrolling back thru pages in my terminal.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/235100", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137808/" ] }
235,112
dpkg-reconfigure exim4-config asks for a domain name to "qualify" email addresses of local users such as root . Let's say I've set this setting to qualified.example.com - this causes all email sent to simply root to go to [email protected] . I instead want all email to root to be sent to [email protected] , but I want the qualified domain name setting left set to qualified.example.com for other reasons. I've added this line to /etc/aliases root: [email protected] And I've also put [email protected] in /root/.forward I've run newaliases and restarted exim , but no matter what I do, mail to root continues to always try to send to [email protected] , which doesn't even exist. How can I force email to root to go to [email protected] ? This is on Ubuntu Server 14.04 My /etc/exim4/update-exim4.conf.conf looks like this: dc_eximconfig_configtype='internet' dc_other_hostnames='' dc_local_interfaces='127.0.0.1' dc_readhost='' dc_relay_domains='' dc_minimaldns='false' dc_relay_nets='' dc_smarthost='' CFILEMODE='644' dc_use_split_config='false' dc_hide_mailname='' dc_mailname_in_oh='true' dc_localdelivery='mail_spool' When I ran dpkg-reconfigure exim4-config I answered the qualified domain question like so: The 'mail name' is the domain name used to 'qualify' mail addresses without a domain name. This name will also be used by other programs. It should be the single, fully qualified domain name (FQDN). Thus, if a mail address on the local host is [email protected], the correct value for this option would be example.org. This name won't appear on From: lines of outgoing messages if rewriting is enabled. System mail name: qualified.example.com_________ Although that setting doesn't appear in /etc/exim4/update-exim4.conf.conf . Should it? I've noticed that the same issue happens on my Debian servers too. I must be completely misunderstanding something about Exim and/or the /etc/aliases file, because they all seem to ignore my /etc/aliases root: [email protected] entry and they always send root's mail to [email protected] no matter what I try. It also seems odd that a simple forwarding rule is so dependent on the mail servers main configuration?
Your host doesn't sufficiently know that it is supposed to be qualified.example.com . A local delivery to root is rewritten as [email protected] , which is (wrongly) considered to be elsewhere, so an off-host delivery is attempted. You need to complete the process telling exim4 that your local host really is qualified.example.com . Then, when it delivers to root , rewritten as [email protected] it will consider this as local delivery. It will then check the /etc/aliases file and perform off-host delivery to [email protected] per your instructions. Let's assume your host's real DNS name is myhost.contoso.com . Rerun dpkg-reconfigure exim4-config and include these settings: System mail name: myhost.contoso.com Other destinations for which [local] mail is accepted: myhost : qualified.example.com Domains to relay mail for: {empty} Machines to relay mail for: {empty} Then run update-exim4.conf and invoke-rc.d exim4 restart
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235112", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/68915/" ] }
235,116
I have been wanting to read systemd-journal by running/using journalctl -b . Now if I run it as a user I get the following :- $ journalctl -bHint: You are currently not seeing messages from other users and the system Users in the 'systemd-journal' group can see all messages. Pass -q to turn off this notice.No journal files were opened due to insufficient permissions. After this I ran a grep in /etc/group to see if such a group exists. $ sudo grep systemd-journal /etc/groupsystemd-journal:x:102:systemd-journal-remote:x:128: then I tried to add the user to that group :- $ sudo useradd -G systemd-journal shirishuseradd: user 'shirish' already exists You can see what it says. I used the id command to find which groups shirish belongs to $ id shirishuid=1000(shirish) gid=1000(shirish) groups=1000(shirish),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),110(lpadmin),113(scanner),119(bluetooth),131(kvm),132(libvirt) As can be seen I do not shirish being member of systemd-journal.
You don't use useradd to add a user to a group. You use useradd to create a user, hence the error message. Try: # usermod -a -G systemd-journal shirish or # gpasswd -a shirish systemd-journal In either case, you need to log in again to make it take effect. A quick-and-dirty way of doing this in a running shell is: $ exec su - shirish
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235116", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/50490/" ] }
235,118
So to be precise I'm trying to delay the startup of "deluge-daemon" on my raspberry pi 2. Somehow the USB (NTFS) only gets automounted (I am using the default automount in Raspbian) after the X-server startup (although I wouldn't even really need the X-server) and Deluge seems to start somewhat earlier than the USB gets mounted and I get the permission problem, because the USB is not mounted yet and have to restart Deluge for it to start to work properly... So I tried lowering the priority and running it only on runlevel 5: sudo update-rc.d deluge-daemon start 20 5 . stop 80 0 1 6 . It doesn't really help. I tried editing the deluge-daemon startup script and adding a sleep 1m in the start case of the startup script. It works then and gets mounted after the USB is already mounted, but the problem is that it now slows down every time I try to start the deluge-daemon service, so every time it takes a minute after I decided to stop and start the process manually... Any help would be appreciated. There has got to be a way to delay the bootup without affecting the general start script...
You don't use useradd to add a user to a group. You use useradd to create a user, hence the error message. Try: # usermod -a -G systemd-journal shirish or # gpasswd -a shirish systemd-journal In either case, you need to log in again to make it take effect. A quick-and-dirty way of doing this in a running shell is: $ exec su - shirish
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235118", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137808/" ] }
235,158
How to check the filesystem type of a logical volume using lvm or any other utility? For example, if my logical volume is /dev/vg1/lv1 then how to check its filesystem type? I have made a ext4 filesystem in the logical volume using mkfs -t ext4 /dev/vg1/lv1 . But don't know how to verify it. I could not see any option for thin is lvm ?
Same as you would with any other block device. e.g. file -s /dev/vg1/lv1 If /dev/vg1/lv1 is a symbolic link, you'll also need file 's -L (aka --dereference ) option to de-reference it (i.e. follow it to the real device node it's pointing to): file -L -s /dev/vg1/lv1 BTW, it's OK to use -L on a regular file. If it's ext4, it'll say something like: /dev/vg1/lv1: Linux rev 1.0 ext4 filesystem data, UUID=xxxx, volume name "yyyy" (needs journal recovery) (extents) (large files) (huge files) Alternatively, you could run blkid /dev/vg1/lv1 . That would report something like: /dev/vg1/lv1: LABEL="yyyy" UUID="xxxx" TYPE="ext4" From man file : -s, --special-files Normally, file only attempts to read and determine the type of argument files which stat(2) reports are ordinary files. This prevents problems, because reading special files may have peculiar consequences. Specifying the -s option causes file to also read argument files which are block or character special files. This is useful for determining the filesystem types of the data in raw disk partitions, which are block special files. This option also causes file to disregard the file size as reported by stat(2) since on some systems it reports a zero size for raw disk partitions.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/235158", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/109220/" ] }
235,213
I am using Ubuntu Server and I am curious if there is anyway to log what username and password a potential attacker has tried. I can grep /var/log/auth.log and see all the failed attempts but I would like to see what username and passwords they are trying.
You can visualise the failed user names after you turn up the verbosity of the log in sshd_config ¹, but there is no way to see the failed passwords as this could be a potential security issue and would violates the privacy of users (for example you could mistype your password and it would be leaked into some log file). All the passwords are handled as extremely sensitive data and only stored in memory and never written to a log so they will not be able to leak out of their security context. To do this, you should use some specially crafted honey-pot custom-made for this use case, not standard production security products. ¹ See man sshd_config for more information
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235213", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137895/" ] }
235,223
I'm trying to include some env vars into a Makefile. The env file looks like: FOO=barBAZ=quux Note there's no leading export to each env var. If I add the leading export and just include the env file in the Makefile, everything works as it should. But I need to keep the env vars sans leading export . That prevents me from just using include envfile in the Makefile. I've also tried doing something like this: sed '/^#/!s/^/export /' envfile > $(BUILDDIR)/envinclude $(BUILDDIR)/env But doing that cause make to throw an error because the env file isn't there for including.
If you are using gnu make, what should work is to include the envfile file, thenexport the list of vars got from the same file: #!makeinclude envfileexport $(shell sed 's/=.*//' envfile)test: env
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/235223", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/14476/" ] }
235,230
Need to verify whether it is installed or not before the program can run.
Type in the shell: pydoc modules . This will list modules and you can grep the module which you want. Found on stackoverflow here
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235230", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/124122/" ] }
235,271
I wish to perform a command ever 10 seconds, and have it executed in the background (thereby eliminating watch ?). All the answers show something like the following, but this will execute ever 11 to 14 seconds. How can this be accomplished? while true; do # perform command that takes between 1 and 4 seconds sleep 10done
How about: ( # In a subshell, for isolation, protecting $! while true; do perform-command & # in the background sleep 10 ; ### If you want to wait for a perform-command ### that happens to run for more than ten seconds, ### uncomment the following line: # wait $! ; ### If you prefer to kill a perform-command ### that happens to run for more than ten seconds, ### uncomment the following line instead: # kill $! ; ### (If you prefer to ignore it, uncomment neither.) done) ETA: With all those comments, alternatives, and the subshell for extra protection, that looks a whole lot more complicated than it started. So, for comparison, here's what it looked like before I started worrying about wait or kill , with their $! and need for isolation: while true; do perform-command & sleep 10 ; done The rest is really just for when you need it.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235271", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137912/" ] }
235,272
I'm trying to set my tmux window's title to be the current directory that I am in. Now pane_current_path is perfect for this, but it prints the full path in my machine. Is it possible to run pane_current_path though some formatting and only print out the current directory? Currently using it like this setw -g window-status-current-format "#{pane_current_path}"setw -g window-status-format "#{pane_current_path}"
How about: ( # In a subshell, for isolation, protecting $! while true; do perform-command & # in the background sleep 10 ; ### If you want to wait for a perform-command ### that happens to run for more than ten seconds, ### uncomment the following line: # wait $! ; ### If you prefer to kill a perform-command ### that happens to run for more than ten seconds, ### uncomment the following line instead: # kill $! ; ### (If you prefer to ignore it, uncomment neither.) done) ETA: With all those comments, alternatives, and the subshell for extra protection, that looks a whole lot more complicated than it started. So, for comparison, here's what it looked like before I started worrying about wait or kill , with their $! and need for isolation: while true; do perform-command & sleep 10 ; done The rest is really just for when you need it.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235272", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137927/" ] }
235,290
I've the script which loads the SSH key from the variable (as part of script in CI environment) in order to not keep the private file in the public repository, however ssh-add complains about the wrong permissions (and it seems it's not possible to bypass it ). So my approach is to find the method of changing the permission of anonymous pipe which is created on the fly. For example: $ stat <(:) File: ‘/dev/fd/63’ Size: 0 Blocks: 0 IO Block: 512 fifoDevice: 397f3928h/964639016d Inode: 818277067 Links: 0Access: (0660/prw-rw----) Uid: ( 501/ kenorb) Gid: ( 20/ staff)Access: 2015-10-10 22:33:30.498640000 +0100Modify: 2015-10-10 22:33:30.498640000 +0100Change: 2015-10-10 22:33:30.498640000 +0100 Birth: 2015-10-10 22:33:30.498640000 +0100 shows 0660 permission. I've checked my umask and it seems it has nothing to do with that. Here is a simple test (on OS X, which by default has 0660): $ ssh-add <(cat ~/.ssh/id_rsa)@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ WARNING: UNPROTECTED PRIVATE KEY FILE! @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Permissions 0660 for '/dev/fd/63' are too open.It is required that your private key files are NOT accessible by others.This private key will be ignored. On Linux it seems to work, because it's 0500 by default. Where this permission is controlled from? To clarify, I'm not looking to change the permission of any file, as I'd like to use an anonymous pipe. The question is: How do I temporary change the permission of a pipe?
So far I've found the following workaround using named FIFO: $ mkfifo -m 600 fifo$ cat ~/.ssh/id_rsa >fifo | ssh-add fifoIdentity added: fifo (fifo) where the option -m sets the FIFO permission.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235290", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/21471/" ] }
235,335
I started thinking about this issue in the context of etiquette on the Linux Kernel Mailing list. As the world's best known and arguably most successful and important free software project, the Linux kernel gets plenty of press. And the project founder and leader, Linus Torvalds, clearly needs no introduction here. Linus occasionally attracts controversy with his flames on the LKML. These flames are frequently, by his own admission, to do with breaking user space. Which brings me to my question. Can I have some historical perspective on why breaking user space is such a bad thing? As I understand it, breaking user space would require fixes on the application level, but is this such a bad thing, if it improves the kernel code? As I understand it, Linus' stated policy is that not breaking user space trumps everything else, including code quality. Why is this so important, and what are the pros and cons of such a policy? (There are clearly some cons to such a policy, consistently applied, since Linus occasionally has "disagreements" with his top lieutenants on the LKML on exactly this topic. As far as I can tell, he always gets his way in the matter.)
The reason is not a historical one but a practical one. There are many many many programs that run on top of the Linux kernel; if a kernel interface breaks those programs then everybody would need to upgrade those programs. Now it's true that most programs do not in fact depend on kernel interfaces directly (the system calls ), but only on interfaces of the C standard library (C wrappers around the system calls). Oh, but which standard library? Glibc? uClibC? Dietlibc? Bionic? Musl? etc. But there are also many programs that implement OS-specific services and depend on kernel interfaces that are not exposed by the standard library. (On Linux, many of these are offered through /proc and /sys .) And then there are statically compiled binaries. If a kernel upgrade breaks one of these, the only solution would be to recompile them. If you have the source: Linux does support proprietary software too. Even when the source is available, gathering it all can be a pain. Especially when you're upgrading your kernel to fix a bug with your hardware. People often upgrade their kernel independently from the rest of their system because they need the hardware support. In the words of Linus Torvalds : Breaking user programs simply isn't acceptable. (…) We know that people use old binaries for years and years, and that making a new release doesn't mean that you can just throw that out. You can trust us. He also explains that one reason to make this a strong rule is to avoid dependency hell where you'd not only have to upgrade another program to get some newer kernel to work, but also have to upgrade yet another program, and another, and another, because everything depends on a certain version of everything. It's somewhat ok to have a well-defined one-way dependency. It's sad, but inevitable sometimes. (…) What is NOT ok is to have a two-way dependency. If user-space HAL code depends on a new kernel, that's ok, although I suspect users would hope that it wouldn't be "kernel of the week", but more a "kernel of the last few months" thing. But if you have a TWO-WAY dependency, you're screwed. That means that you have to upgrade in lock-step, and that just IS NOT ACCEPTABLE. It's horrible for the user, but even more importantly, it's horrible for developers, because it means that you can't say "a bug happened" and do things like try to narrow it down with bisection or similar. In userspace, those mutual dependencies are usually resolved by keeping different library versions around; but you only get to run one kernel, so it has to support everything people might want to do with it. Officially , backward compatibility for [system calls declared stable] will be guaranteed for at least 2 years. In practice though, Most interfaces (like syscalls) are expected to never change and always be available. What does change more often is interfaces that are only meant to be used by hardware-related programs, in /sys . ( /proc , on the other hand, which since the introduction of /sys has been reserved for non-hardware-related services, pretty much never breaks in incompatible ways.) In summary, breaking user space would require fixes on the application level and that's bad because there's only one kernel, which people want to upgrade independently of the rest of their system, but there are many many applications out there with complex interdependencies. It's easier to keep the kernel stable that to keep thousands of applications up-to-date on millions of different setups.
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/235335", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/4671/" ] }
235,361
I have been using the following lines in my bashrc file for quite some time now and suddenly now I have an error. Here are the lines: make(){ /usr/bin/make "$@" 2>&1 | sed -E -e "s/error/ $(echo -e "\\033[31m" ERROR "\\033[0m"/g)" -e "s/warning/ $(echo -e "\\033[0;33m" WARNING "\\033[0m"/g)" return ${PIPESTATUS[0]}} Here is the error: bash: /home/username/.bashrc: line 175: syntax error near unexpected token `('bash: /home/username/.bashrc: line 175: `make()'
You probably have an alias for make somewhere earlier in the files thatbash reads on startup. Try alias -p to list them, and adding unalias make in front of the function.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235361", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/70847/" ] }
235,396
I have several files with encoding issues in their file names (German umlauts, burned on CD with Windows, read by Windows and synced to Linux with Seafile. Something, somewhere went wrong...).Bash and zsh only show "?" instead of umlauts, stat shows something like $ stat Erg�nzung.doc File: ‘Erg\344nzung.doc’Size: 2609152 Blocks: 5096 IO Block: 4096 regular fileDevice: 806h/2054d Inode: 12321475 Links: 1 I can enter the filename only with autocompletion. How do I rename the file? The affected files seem to be unreadable by LibreOffice (or other programs for other file types), they complain about "No such file or device". I was thinking about mv --by-inode 12321475 Ergänzung.doc , but there's no --by-inode switch for mv . What else can I do?
You could try: find . -inum 12321475 -exec mv {} new-filename \; or find . -inum 12321475 -print0 | xargs -0 mv -t new-filename Generally I prefer xargs over exec. Google for why. It's tricky though. See Find -exec + vs find | xargs. Which one to choose?
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235396", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/63453/" ] }
235,414
I have the current libvirt 1.2.20i want to pass to my machine create with virt-managersome qemu flags.I edited the file and add </devices> <qemu:commandline> <qemu:arg value='-L pc-bios'/> </qemu:commandline></domain> But doesn't worki also tried to edit from virsh virsh edit domain and put <qemu:commandline> <qemu:arg value='-L pc-bios'/> </qemu:commandline> But give me this error errore: XML document failed to validate against schema: Unable to validate doc against /usr/share/libvirt/schemas/domain.rngElement domain has extra content: qemu:commandlineFailed. Try again? [y,n,i,f,?]: How to pass correctly qemu command line?Thanks
elbarna's own answer is the way to go for configuration options "natively" supported by libvirt (and thus its domain XML).For qemu commandline arguments (and more) not supported by libvirt, you need to include qemu's XML namespace declaration in the 'domain' root element: <domain type='kvm' xmlns:qemu='http://libvirt.org/schemas/domain/qemu/1.0'> Reference: https://libvirt.org/drvqemu.html#qemucommand
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235414", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/80389/" ] }
235,449
man ksoftirqd indicates that: If ksoftirqd is taking more than a tiny percentage of CPU time, this indicates the machine is under heavy soft interrupt load. I'm working with a Debian Wheezy system under generally high system utilization in which ksoftirqd processes utilizes excessive cpu and disk resources for a short period of time. During that time, the system operates at a snails pace. How can one begin to understand what the root cause is for this ksoftirqd resource utilization spikes?
Check /proc/interrupts to find if one of or more interrupts occur excessively. Hint: Several thousand interrupts per second are no cause for alarm. Excessive interrupts (aka interrupt storms) can have multiple reasons, one of them even being hardware issues (noisy interrupt line). To further answer your question we need to know what OS on what hardware you use.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235449", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/37916/" ] }
235,461
I would like to build Debian package from source, using dpkg-buildpackage . I have downloaded package source: apt-get -t wheezy-backports source gnucash Inside the file gnucash-2.6.9/configure I see, that there are options which can be selected/deselected when building the package. Debian maintainer has already made the decision for me. But if I want disable some options, how should I do it? Lets say, I want to compile the package without --enable-aqbanking . This option appears in several configuration files: $ grep -rl enable-aqbanking gnucash-2.6.9/gnucash-2.6.9/packaging/gnucash.specgnucash-2.6.9/packaging/gnucash.spec.ingnucash-2.6.9/configure.acgnucash-2.6.9/configure Which of those should I edit? What is the proper way to do it?
OK, take a look at gnucash-2.6.x/debian/rules . Find the line that says override_dh_auto_configure: (line 23 in my case), and add your overrides below it. In your case --enable-aqbanking is already there (for wheezy-backports at least), so simply delete it. More info can be found in the man page . Update: In addition, sometimes there's a variable in the rules file responsible for passing custom stuff to configure . It's usually at the top of the file and is called DEB_CONFIGURE_EXTRA_FLAGS .
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235461", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/43007/" ] }
235,465
I want to send a list of all folders including one level down to a txt file. Excluding some named folders and no files.Imagine a folder structure like this. CAPS are folders. FOLDER 1.hiddenTEMPsomefile==================FOLDER 2.hiddenTEMPDATA1DATA2somefile================FOLDER 3.hiddenTEMPDATA1somefile I would like to run "insert magic command here" and end up with an output that looks like below FOLDER 1FOLDER 2DATA1DATA2FOLDER 3DATA1
OK, take a look at gnucash-2.6.x/debian/rules . Find the line that says override_dh_auto_configure: (line 23 in my case), and add your overrides below it. In your case --enable-aqbanking is already there (for wheezy-backports at least), so simply delete it. More info can be found in the man page . Update: In addition, sometimes there's a variable in the rules file responsible for passing custom stuff to configure . It's usually at the top of the file and is called DEB_CONFIGURE_EXTRA_FLAGS .
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235465", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138067/" ] }
235,477
Cups "add printer" page returns forbidden on Web Interface on http://localhost:631/admin I tried adding my main user to "lp" and restarting, but no change. I also tried setting at the top of the cups.conf SystemGroup printadmin and doing sudo systemctl restart cups to no avail. Here is the relevant cups.conf # Restrict access to configuration files...<Location /admin/conf> AuthType Default Require user @SYSTEM Order allow,deny</Location> I'm just trying to add a printer using the web interface, but something about the permissions doesn't allow my user credentials to work. There is no group named SYSTEM or lpadmin.
Update: On Fedora 25 this is now default... So if you're having this problem on Fedora 25+, you likely messed up your config or you have a different problem. But this might still be useful users of old installs of CentOS/RHEL... you should not be using Fedora 24 at this point. Find /etc/cups/cups-files.conf as root. Look for the line with SystemGroup sys root add wheel to it. The following two liner should do it for you on Fedora 24 sudo sed -i '/SystemGroup sys root$/ s/$/ wheel/' /etc/cups/cups-files.conf sudo systemctl restart cups
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235477", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/38213/" ] }
235,507
I'm reducing the question to (I believe) the simplest case. Let's say I have a script myscript.sh with the following contents: #!/bin/bashIFS='%20'echo "$*" If I run the command as follows, the output will look like: me@myhost ~ $ ./myscript.sh fee fi fo fumfee%fi%fo%fum This is expected behavior, as described in the bash man page: * Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a sin- gle word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equiva- lent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are sepa- rated by spaces. If IFS is null, the parameters are joined without intervening separators. However, what I would like to get is the output: fee%20fi%20fo%20fum Thus using a multiple character separator field rather than a single character. Is there a way to do this that is native to bash ? UPDATE: Based on the data from mikeserv below, and the writeup at Why is printf better than echo? , I ended up doing the following (again reduced to simplest case as in the example above): #!/bin/bashword="$1"shiftif [ "$#" -gt 0 ] ; then word="$word$(printf '%%20%s' "$@")"fiprintf '%s\n' "$word"unset word
printf applies its format string to each argument that follows it on output. It is a bash shell builtin and can be used to apply a delimiter string to a list of arguments - kind of. For example: printf %s:delimit: arg1 arg2 arg3 arg1:delimit:arg2:delimit:arg3:delimit: The thing is, printf doesn't stop applying its format string at the end of its arguments, and so the last one gets an appended delimiter. This can be handled in some cases: printf %b:delimit: \\0150 \\0145 \\0171\\c h:delimit:e:delimit:y printf interprets C and octal escapes as %b ytes with a certain kind of format, and also with the %b format you \c ut its output at a certain point, which is why printf does not follow the y above with a :delimit: string as its format string would otherwise indicate. So if you want every argument literally interpreted and no trailing delimiter, then you have to address the problem within the argument list itself: set -- arg1 arg2 arg3for arg do shift set -- "$@" :delimit: "$arg"done; shiftprintf %s "$@" arg1:delimit:arg2:delimit:arg3
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235507", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/135943/" ] }
235,512
I recently installed Manjaro Linux, an Arch based system. I didn't specify my drive /dev/sda6 as my /home in the setup. So now I have a /home in my / drive. How can I mount my /dev/sda6 as my /home ? I tried editing /etc/fstab file and rebooting but it made no difference. Can you help me to fix this?
printf applies its format string to each argument that follows it on output. It is a bash shell builtin and can be used to apply a delimiter string to a list of arguments - kind of. For example: printf %s:delimit: arg1 arg2 arg3 arg1:delimit:arg2:delimit:arg3:delimit: The thing is, printf doesn't stop applying its format string at the end of its arguments, and so the last one gets an appended delimiter. This can be handled in some cases: printf %b:delimit: \\0150 \\0145 \\0171\\c h:delimit:e:delimit:y printf interprets C and octal escapes as %b ytes with a certain kind of format, and also with the %b format you \c ut its output at a certain point, which is why printf does not follow the y above with a :delimit: string as its format string would otherwise indicate. So if you want every argument literally interpreted and no trailing delimiter, then you have to address the problem within the argument list itself: set -- arg1 arg2 arg3for arg do shift set -- "$@" :delimit: "$arg"done; shiftprintf %s "$@" arg1:delimit:arg2:delimit:arg3
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235512", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138094/" ] }
235,554
I managed to write the following script: #!/bin/bash#files listfile1=/tmp/1wall_long.txtfile2=/tmp/1wall_test1.txtfile3=/tmp/1wall_test2.txtfile4=/tmp/1wall_test3.txtfile5=/tmp/3mt_long.txtfile6=/tmp/3mt_OpenSpace_test1.txtfile7=/tmp/3mt_OpenSpace_test2.txtfile8=/tmp/3mt_OpenSpace_test3.txtfile9=/tmp/3rooms_test1.txtfile10=/tmp/3rooms_test2.txtfile11=/tmp/3rooms_test3.txtfile12=/tmp/20mt_OpenSpace_test1.txtfile13=/tmp/20mt_OpenSpace_test2.txtfile14=/tmp/20mt_OpenSpace_test3.txt#script for 1wall_long fileif [ ! -e "$file1" ]; then #check if the file exist echo "File 1wall_long.txt does not exist" #if not exist print echo outputelse sed -i -e 's/- /-/g' $file1 #remove space on the first 10 values awk '{print $7}' $file1 > /tmp/1wall_long_S.txt #print the column number 7 and copy the output in a file rm $file1 #remove old filefi The script is repeated for all files described in the variable (basically I have the same script repeated 14 times with different variables)Is there a better way to do it and what is the best practice in these situations ?
Personally, I would avoid hardcoding the file names. That is rarely a good idea and it is usually better to have the option of passing target files as arguments. Additionally, you are modifying the file in place and then deleting the original. That's not efficient, just modify the file on the fly and print the 7th column without having to write it to disk. For example: #!/usr/bin/env bash## Iterate over the file names givenfor file in "$@"; do ## Get the output file's name. The ${file%.*} is ## the file's anme without its extension. outfile="${file%.*}"_S.txt ## If the file exists if [ -e "$file" ]; then ## remove the spaces and print the 7th column sed 's/- /-/g' "$file" | awk '{print $7}' > "$outfile" && ## Delete the original but only if the step ## above was successful (that's what the && does)/ rm "$file" else ## If the file doesn't exist, print an error message echo "The file $file does not exist!" fidone Then, you can run the script like this: foo.sh /tmp/1wall_long.txt /tmp/1wall_test1.txt /tmp/1wall_test2.txt /tmp/1wall_test3.txt /tmp/20mt_OpenSpace_test1.txt /tmp/20mt_OpenSpace_test2.txt /tmp/20mt_OpenSpace_test3.txt /tmp/3mt_long.txt /tmp/3mt_OpenSpace_test1.txt /tmp/3mt_OpenSpace_test2.txt /tmp/3mt_OpenSpace_test3.txt /tmp/3rooms_test1.txt /tmp/3rooms_test2.txt /tmp/3rooms_test3.txt If you do want to have the names hard coded, just use an array as suggested by @choroba: #!/usr/bin/env bashfiles=(/tmp/1wall_long.txt /tmp/1wall_test1.txt /tmp/1wall_test2.txt /tmp/1wall_test3.txt /tmp/20mt_OpenSpace_test1.txt /tmp/20mt_OpenSpace_test2.txt /tmp/20mt_OpenSpace_test3.txt /tmp/3mt_long.txt /tmp/3mt_OpenSpace_test1.txt /tmp/3mt_OpenSpace_test2.txt /tmp/3mt_OpenSpace_test3.txt /tmp/3rooms_test1.txt /tmp/3rooms_test2.txt /tmp/3rooms_test3.txt )## Iterate over the file names givenfor file in "${files[@]}"; do ## Get the output file's name. The ${file%.*} is ## the file's anme without its extension. outfile="${file%.*}"_S.txt ## If the file exists if [ -e "$file" ]; then ## remove the spaces and print the 7th column sed 's/- /-/g' "$file" | awk '{print $7}' > "$outfile" && ## Delete the original but only if the step ## above was successful (that's what the && does)/ rm "$file" else ## If the file doesn't exist, print an error message echo "The file $file does not exist!" fidone
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235554", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138120/" ] }
235,565
I used to login to a remote machine( I have to root of this machine) using key. Both my local machine and remote machine is in f23. From last few days, I can't login to this machine using key. It is asking for password. Here is the ssh -vvv: ssh -vvv avetaOpenSSH_7.1p1, OpenSSL 1.0.2d-fips 9 Jul 2015debug1: Reading configuration data /home/rudra/.ssh/configdebug1: /home/rudra/.ssh/config line 4: Applying options for avetadebug1: Reading configuration data /etc/ssh/ssh_configdebug1: /etc/ssh/ssh_config line 56: Applying options for *debug2: ssh_connect: needpriv 0debug1: Connecting to phy-aveta.physics.uu.se [130.238.194.143] port 22.debug1: Connection established.debug1: identity file /home/rudra/.ssh/id_rsa type 1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_rsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_dsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_dsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_ecdsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_ecdsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_ed25519 type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_7.1debug1: Remote protocol version 2.0, remote software version OpenSSH_7.1debug1: match: OpenSSH_7.1 pat OpenSSH* compat 0x04000000debug2: fd 3 setting O_NONBLOCKdebug1: Authenticating to phy-aveta.physics.uu.se:22 as 'rudra'debug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:16debug3: load_hostkeys: loaded 1 keys from phy-aveta.physics.uu.sedebug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521debug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT receiveddebug2: kex_parse_kexinit: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],ssh-ed25519,ssh-rsadebug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1,[email protected],[email protected],[email protected],[email protected],hmac-md5,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1,[email protected],[email protected],[email protected],[email protected],hmac-md5,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: none,[email protected],zlibdebug2: kex_parse_kexinit: none,[email protected],zlibdebug2: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: kex_parse_kexinit: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1debug2: kex_parse_kexinit: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: kex_parse_kexinit: none,[email protected]: kex_parse_kexinit: none,[email protected]: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug1: kex: server->client [email protected] <implicit> nonedebug1: kex: client->server [email protected] <implicit> nonedebug1: kex: [email protected] need=64 dh_need=64debug1: kex: [email protected] need=64 dh_need=64debug1: expecting SSH2_MSG_KEX_ECDH_REPLYdebug1: Server host key: ecdsa-sha2-nistp256 SHA256:F34tt6QLRDt6Qm45eHOFhYGS5DSxYrThhR2lbBHNXesdebug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:16debug3: load_hostkeys: loaded 1 keys from phy-aveta.physics.uu.sedebug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:14debug3: load_hostkeys: loaded 1 keys from 130.238.194.143debug1: Host 'phy-aveta.physics.uu.se' is known and matches the ECDSA host key.debug1: Found key in /home/rudra/.ssh/known_hosts:16debug2: set_newkeys: mode 1debug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug2: set_newkeys: mode 0debug1: SSH2_MSG_NEWKEYS receiveddebug1: Roaming not allowed by serverdebug1: SSH2_MSG_SERVICE_REQUEST sentdebug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug2: key: /home/rudra/.ssh/id_rsa (0x562e17c87070),debug2: key: /home/rudra/.ssh/id_dsa ((nil)),debug2: key: /home/rudra/.ssh/id_ecdsa ((nil)),debug2: key: /home/rudra/.ssh/id_ed25519 ((nil)),debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_lookup gssapi-keyexdebug3: remaining preferred: gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_is_enabled gssapi-keyexdebug1: Next authentication method: gssapi-keyexdebug1: No valid Key exchange contextdebug2: we did not send a packet, disable methoddebug3: authmethod_lookup gssapi-with-micdebug3: remaining preferred: publickey,keyboard-interactive,passworddebug3: authmethod_is_enabled gssapi-with-micdebug1: Next authentication method: gssapi-with-micdebug1: Unspecified GSS failure. Minor code may provide more informationNo Kerberos credentials availabledebug1: Unspecified GSS failure. Minor code may provide more informationNo Kerberos credentials availabledebug1: Unspecified GSS failure. Minor code may provide more informationdebug1: Unspecified GSS failure. Minor code may provide more informationNo Kerberos credentials availabledebug2: we did not send a packet, disable methoddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Offering RSA public key: /home/rudra/.ssh/id_rsadebug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,passworddebug1: Trying private key: /home/rudra/.ssh/id_dsadebug3: no such identity: /home/rudra/.ssh/id_dsa: No such file or directorydebug1: Trying private key: /home/rudra/.ssh/id_ecdsadebug3: no such identity: /home/rudra/.ssh/id_ecdsa: No such file or directorydebug1: Trying private key: /home/rudra/.ssh/id_ed25519debug3: no such identity: /home/rudra/.ssh/id_ed25519: No such file or directorydebug2: we did not send a packet, disable methoddebug3: authmethod_lookup passworddebug3: remaining preferred: ,passworddebug3: authmethod_is_enabled passworddebug1: Next authentication method: [email protected]'s password: I have deleted .ssh , .config and .cache from the remote and redo ssh-copy-id , without any help. To troubleshoot, I have createed another user, did ssh-copy-id and that one is working fine. ssh -vvv for that working machine is: ssh -vvv [email protected] OpenSSH_7.1p1, OpenSSL 1.0.2d-fips 9 Jul 2015debug1: Reading configuration data /home/rudra/.ssh/configdebug1: Reading configuration data /etc/ssh/ssh_configdebug1: /etc/ssh/ssh_config line 56: Applying options for *debug2: ssh_connect: needpriv 0debug1: Connecting to phy-aveta.physics.uu.se [130.238.194.143] port 22.debug1: Connection established.debug1: identity file /home/rudra/.ssh/id_rsa type 1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_rsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_dsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_dsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_ecdsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_ecdsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_ed25519 type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/rudra/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_7.1debug1: Remote protocol version 2.0, remote software version OpenSSH_7.1debug1: match: OpenSSH_7.1 pat OpenSSH* compat 0x04000000debug2: fd 3 setting O_NONBLOCKdebug1: Authenticating to phy-aveta.physics.uu.se:22 as 'rudra2'debug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:16debug3: load_hostkeys: loaded 1 keys from phy-aveta.physics.uu.sedebug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521debug1: SSH2_MSG_KEXINIT sentdebug1: SSH2_MSG_KEXINIT receiveddebug2: kex_parse_kexinit: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],ssh-ed25519,ssh-rsadebug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1,[email protected],[email protected],[email protected],[email protected],hmac-md5,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1,[email protected],[email protected],[email protected],[email protected],hmac-md5,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: kex_parse_kexinit: none,[email protected],zlibdebug2: kex_parse_kexinit: none,[email protected],zlibdebug2: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: kex_parse_kexinit: [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1debug2: kex_parse_kexinit: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519debug2: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]: kex_parse_kexinit: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: kex_parse_kexinit: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: kex_parse_kexinit: none,[email protected]: kex_parse_kexinit: none,[email protected]: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug1: kex: server->client [email protected] <implicit> nonedebug1: kex: client->server [email protected] <implicit> nonedebug1: kex: [email protected] need=64 dh_need=64debug1: kex: [email protected] need=64 dh_need=64debug1: expecting SSH2_MSG_KEX_ECDH_REPLYdebug1: Server host key: ecdsa-sha2-nistp256 SHA256:F34tt6QLRDt6Qm45eHOFhYGS5DSxYrThhR2lbBHNXesdebug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:16debug3: load_hostkeys: loaded 1 keys from phy-aveta.physics.uu.sedebug3: hostkeys_foreach: reading file "/home/rudra/.ssh/known_hosts"debug3: record_hostkey: found key type ECDSA in file /home/rudra/.ssh/known_hosts:14debug3: load_hostkeys: loaded 1 keys from 130.238.194.143debug1: Host 'phy-aveta.physics.uu.se' is known and matches the ECDSA host key.debug1: Found key in /home/rudra/.ssh/known_hosts:16debug2: set_newkeys: mode 1debug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug2: set_newkeys: mode 0debug1: SSH2_MSG_NEWKEYS receiveddebug1: Roaming not allowed by serverdebug1: SSH2_MSG_SERVICE_REQUEST sentdebug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug2: key: /home/rudra/.ssh/id_rsa (0x55c98f7eb080),debug2: key: /home/rudra/.ssh/id_dsa ((nil)),debug2: key: /home/rudra/.ssh/id_ecdsa ((nil)),debug2: key: /home/rudra/.ssh/id_ed25519 ((nil)),debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_lookup gssapi-keyexdebug3: remaining preferred: gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_is_enabled gssapi-keyexdebug1: Next authentication method: gssapi-keyexdebug1: No valid Key exchange contextdebug2: we did not send a packet, disable methoddebug3: authmethod_lookup gssapi-with-micdebug3: remaining preferred: publickey,keyboard-interactive,passworddebug3: authmethod_is_enabled gssapi-with-micdebug1: Next authentication method: gssapi-with-micdebug1: Unspecified GSS failure. Minor code may provide more informationNo Kerberos credentials availabledebug1: Unspecified GSS failure. Minor code may provide more informationNo Kerberos credentials availabledebug1: Unspecified GSS failure. Minor code may provide more informationdebug1: Unspecified GSS failure. Minor code may provide more informationNo Kerberos credentials availabledebug2: we did not send a packet, disable methoddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Offering RSA public key: /home/rudra/.ssh/id_rsadebug3: send_pubkey_testdebug2: we sent a publickey packet, wait for replydebug1: Server accepts key: pkalg ssh-rsa blen 279debug2: input_userauth_pk_ok: fp SHA256:xT3VPQUunB3Nv/Pmi6C6Sroc0fa9SlKcQ4d0eF2vxzIdebug3: sign_and_send_pubkey: RSA SHA256:xT3VPQUunB3Nv/Pmi6C6Sroc0fa9SlKcQ4d0eF2vxzIdebug1: Authentication succeeded (publickey).Authenticated to phy-aveta.physics.uu.se ([130.238.194.143]:22).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug1: Requesting [email protected]: Entering interactive session.debug1: client_input_global_request: rtype [email protected] want_reply 0debug2: callback startdebug2: fd 3 setting TCP_NODELAYdebug3: ssh_packet_set_tos: set IP_TOS 0x10debug2: client_session2_setup: id 0debug2: channel 0: request pty-req confirm 1debug1: Sending environment.debug3: Ignored env XDG_VTNRdebug3: Ignored env XDG_SESSION_IDdebug3: Ignored env HOSTNAMEdebug3: Ignored env SHELLdebug3: Ignored env TERMdebug3: Ignored env XDG_MENU_PREFIXdebug3: Ignored env VTE_VERSIONdebug3: Ignored env HISTSIZEdebug3: Ignored env XCRYSDEN_SCRATCHdebug3: Ignored env WINDOWIDdebug3: Ignored env QTDIRdebug3: Ignored env QTINCdebug3: Ignored env QT_GRAPHICSSYSTEM_CHECKEDdebug3: Ignored env XCRYSDEN_TOPDIRdebug3: Ignored env USERdebug3: Ignored env LS_COLORSdebug3: Ignored env DESKTOP_AUTOSTART_IDdebug3: Ignored env SSH_AUTH_SOCKdebug3: Ignored env SESSION_MANAGERdebug3: Ignored env PATHdebug3: Ignored env MAILdebug3: Ignored env DESKTOP_SESSIONdebug3: Ignored env QT_IM_MODULEdebug3: Ignored env XDG_SESSION_TYPEdebug3: Ignored env PWDdebug1: Sending env XMODIFIERS = @im=ibusdebug2: channel 0: request env confirm 0debug1: Sending env LANG = en_GB.UTF-8debug2: channel 0: request env confirm 0debug3: Ignored env MODULEPATHdebug3: Ignored env GDM_LANGdebug3: Ignored env LOADEDMODULESdebug3: Ignored env GDMSESSIONdebug3: Ignored env SSH_ASKPASSdebug3: Ignored env HISTCONTROLdebug3: Ignored env HOMEdebug3: Ignored env XDG_SEATdebug3: Ignored env SHLVLdebug3: Ignored env GNOME_DESKTOP_SESSION_IDdebug3: Ignored env XBANDPATHdebug3: Ignored env XDG_SESSION_DESKTOPdebug3: Ignored env LOGNAMEdebug3: Ignored env QTLIBdebug3: Ignored env DBUS_SESSION_BUS_ADDRESSdebug3: Ignored env MODULESHOMEdebug3: Ignored env LESSOPENdebug3: Ignored env WINDOWPATHdebug3: Ignored env XDG_RUNTIME_DIRdebug3: Ignored env DISPLAYdebug3: Ignored env XDG_CURRENT_DESKTOPdebug3: Ignored env XAUTHORITYdebug3: Ignored env BASH_FUNC_module()debug3: Ignored env BASH_FUNC_scl()debug3: Ignored env _debug2: channel 0: request shell confirm 1debug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel_input_status_confirm: type 99 id 0debug2: PTY allocation request accepted on channel 0debug2: channel 0: rcvd adjust 2097152debug2: channel_input_status_confirm: type 99 id 0debug2: shell request accepted on channel 0Last login: Mon Oct 12 12:33:15 2015 from 130.238.194.90[rudra2@phy-aveta ~]$ debug2: client_check_window_change: changeddebug2: channel 0: request window-change confirm 0 I am clueless why in same local-remote combination, one is working and other is not. EDIT .ssh/config for the failed one is: Host aveta User rudra Hostname phy-aveta.physics.uu.se ForwardX11 yes There is no ssh/.config entry for rudra2 , i.e. that worked. Ans to Paul in my local machine I have: tree .ssh/.ssh/├── authorized_keys├── config├── environment├── id_rsa├── id_rsa.pub└── known_hosts In both the remote user, I only have authorized_keys . And both are identical. [root@phy-aveta rudra2]# diff .ssh/authorized_keys /home/rudra/.ssh/authorized_keys [root@phy-aveta rudra2]# Edit 2: Without using ssh/.config I have commented out the part for first user in .ssh/config. http://ur1.ca/nzndx is the ssh -vvv for that. It is still asking for password Edit: Permission The first user...failed one #ls -al /home/rudra/|grep .sshdrwx------. 2 rudra rudra 4096 Oct 12 14:16 .ssh$ls -alF .ssh/total 12Kdrwx------. 2 rudra rudra 4.0K Oct 12 14:16 ./drwxrwxr-x. 36 rudra rudra 4.0K Oct 12 14:30 ../-rw-------. 1 rudra rudra 394 Oct 10 12:01 authorized_keys For 2nd user # ls -al /home/rudra2/|grep .sshdrwx------. 2 rudra2 rudra2 4096 Oct 12 14:16 .ssh$ ls -alF .ssh/total 12drwx------. 2 rudra2 rudra2 4096 Oct 12 14:16 ./drwx------. 4 rudra2 rudra2 4096 Oct 12 14:14 ../-rw-------. 1 rudra2 rudra2 394 Oct 11 09:57 authorized_keys
There it is. Group has write access to ~rudra: $ls -alF .ssh/ total 12Kdrwx------. 2 rudra rudra 4.0K Oct 12 14:16 ./drwxrwxr-x. 36 rudra rudra 4.0K Oct 12 14:30 ../-rw-------. 1 rudra rudra 394 Oct 10 12:01 authorized_keys Thus, sshd refuses to trust the files in ~rudra, and does not use ~rudra/.ssh/authorized_keys, even though its permissions are correct. chmod g-w ~rudra ought to fix it.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235565", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/43074/" ] }
235,582
If I use trap like described e.g. on http://linuxcommand.org/wss0160.php#trap to catch ctrl-c (or similar) and cleanup before exiting then I am changing the exit code returned. Now this probably won't make difference in the real world (e.g. because the exit codes are not portable and on top of that not always unambiguous as discussed in Default exit code when process is terminated? ) but still I am wondering whether there there is really no way to prevent that and return the default error code for interrupted scripts instead? Example (in bash, but my question shouldn't be considered bash-specific): #!/bin/bashtrap 'echo EXIT;' EXITread -p 'If you ctrl-c me now my return code will be the default for SIGTERM. ' _trap 'echo SIGINT; exit 1;' INTread -p 'If you ctrl-c me now my return code will be 1. ' _ Output: $ ./test.sh # doing ctrl-c for 1st readIf you ctrl-c me now my return code will be the default for SIGTERM.$ echo $?130$ ./test.sh # doing ctrl-c for 2nd readIf you ctrl-c me now my return code will be the default for SIGTERM.If you ctrl-c me now my return code will be 1. SIGINT EXIT$ echo $?1 (Edited to remove to make it more POSIX-conform.) (Edited again to make it a bash script instead, my question is not shell-specific though.) Edited to use the portable "INT" for trap in favor of the non-portable "SIGINT". Edited to remove useless curly braces and add potential solution. Update: I solved it now by simply exiting with some error codes hardcoded and trapping EXIT. This might be problematic on certain systems because the error code might differ or the EXIT trap not possible but in my case it's OK enough. trap cleanup EXITtrap 'exit 129' HUPtrap 'exit 130' INTtrap 'exit 143' TERM
Actually, interrupting bash's internal read seems to be a bit different to interrupting a command run by bash. Normally, when you enter trap , $? is set and you can preserve it and exit with the same value: trap 'rc=$?; echo $rc SIGINT; exit $rc' INTtrap 'rc=$?; echo $rc EXIT; exit $rc' EXIT If your script is interrupted when executing a command like sleep or even a builtin like wait , you will see 130 SIGINT130 EXIT and the exit code is 130. However, for read -p , it seems $? is 0 (on my version of bash 4.3.42 anyway). The handling of signals during read might be work in progress, according tothe changes file in my release... (/usr/share/doc/bash/CHANGES) changes between this version, bash-4.3-alpha, and the previous version, bash-4.2-release. New Features in Bash r. When in Posix mode, `read' is interruptible by a trapped signal. After running the trap handler, read returns 128+signal and throws away any partially-read input.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235582", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/117599/" ] }
235,592
Usually I find my answers in the previously answered questions, but not this time (or I don't understand the answers and can't modify them to do what I want them to do), so I'm asking my first question here. My input files look like # -*- coding: utf-8 -*-[attachment][browser][changeset][components]tracopt.versioncontrol.svn.svn_fs.subversionconnector = enabledtracopt.versioncontrol.svn.svn_prop.subversionmergepropertydiffrenderer = enabled tracopt.versioncontrol.svn.svn_prop.subversionmergepropertyrenderer = enabledtracopt.versioncontrol.svn.svn_prop.subversionpropertyrenderer = enabled[header_logo][inherit]file = /etc/trac/trac.ini[logging] I'd like to remove all empty sections like attachment, browser, changeset, header_logo and logging. I'd only keep the sections that aren't empty. The output file should look like # -*- coding: utf-8 -*-[components]tracopt.versioncontrol.svn.svn_fs.subversionconnector = enabledtracopt.versioncontrol.svn.svn_prop.subversionmergepropertydiffrenderer = enabledtracopt.versioncontrol.svn.svn_prop.subversionmergepropertyrenderer = enabledtracopt.versioncontrol.svn.svn_prop.subversionpropertyrenderer = enabled[inherit]file = /etc/trac/trac.ini This should happen in a bash script. I've thought of using sed : looking for a regex \[.+\]\n(\n)+(?=\[) but this doesn't seem to work with sed because I should know in advance how many lines the regex will be and use N accordingly. The regex should also work with EOF instead of the final \[ , but I can probably do this if I find the way to do it for the \[ . Any idea how I could do this? Is there a better way than sed?
It is a bit messy with sed but possible: sed -n ':start/^\[/{ h :loop n /^\[/b start /^$/b loop x;p;g}p' -n means print nothing by default. :start is just a label for a later goto. We match lines beginning [ and start a group ({...}) of commands.We copy the line to the hold space (h). We get the next line (n). If itbegins [ we had an empty section, so goto (b) the start again. If the line is empty (/^$/) we read another line (goto loop). The line is not empty so we exchange the line with the held section header (x), print the section header (p), get the current line back (g) and continue out of the group of commands to print (p) the line. This last (p) also prints non-section headers.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235592", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138133/" ] }
235,605
My binary depends on these boost libraries and respective packages: NAME | PACKAGE:--------------------------------------+-----------------------------------libboost_serialization.so.1.55.0 | libboost-serialization1.55.0libboost_thread.so.1.55.0 | ibboost-thread1.55.0libboost_date_time.so.1.55.0 | libboost-date-time1.55.0libboost_signals.so.1.55.0 | libboost-signals1.55.0 So I'd like to define a list of packages: boostlibnames="libboost-serialization1.55.0 libboost-thread1.55.0 libboost-date-time1.55.0 libboost-signals1.55.0" And now I'd like to check if they are all installed and only then run actual apt-get install . I know apt will automatically check whether the packages are already installed, but I'd like to place in a prompt to the user whether he wants to install missing libraries before doing so. So is there a nice way to check whether all listed libraries (in variable as above) are installed?
The dpkg -s command returns the status of installed packages. For example, on my system, if I run it for firefox which is installed and nedit which isn't, I get: $ dpkg -s firefoxPackage: firefoxStatus: install ok installedPriority: optionalSection: webInstalled-Size: 94341Maintainer: Clement Lefebvre <[email protected]>Architecture: amd64Version: 41.0~linuxmint1+betsyReplaces: firefox-l10n-af, firefox-l10n-ar, firefox-l10n-be, firefox-l10n-bg, firefox-l10n-bn-bd, firefox-l10n-ca, firefox-l10n-cs, firefox-l10n-da, firefox-l10n-de, firefox-l10n-el, firefox-l10n-en-gb, firefox-l10n-en-us, firefox-l10n-eo, firefox-l10n-es, firefox-l10n-et, firefox-l10n-eu, firefox-l10n-fa, firefox-l10n-fi, firefox-l10n-fr, firefox-l10n-fy, firefox-l10n-gl, firefox-l10n-gu, firefox-l10n-he, firefox-l10n-hi, firefox-l10n-hr, firefox-l10n-hu, firefox-l10n-id, firefox-l10n-is, firefox-l10n-it, firefox-l10n-ja, firefox-l10n-kn, firefox-l10n-ko, firefox-l10n-lt, firefox-l10n-lv, firefox-l10n-nb, firefox-l10n-nl, firefox-l10n-nn, firefox-l10n-pl, firefox-l10n-pt, firefox-l10n-pt-br, firefox-l10n-ro, firefox-l10n-ru, firefox-l10n-sk, firefox-l10n-sl, firefox-l10n-sq, firefox-l10n-sr, firefox-l10n-sv, firefox-l10n-th, firefox-l10n-tr, firefox-l10n-uk, firefox-l10n-zhProvides: gnome-www-browser, www-browserBreaks: firefox-l10n-en-usDescription: The Firefox web browser The Mozilla Firefox Web Browser.$ dpkg -s neditdpkg-query: package 'nedit' is not installed and no information is availableUse dpkg --info (= dpkg-deb --info) to examine archive files,and dpkg --contents (= dpkg-deb --contents) to list their contents. So, you can use that command to check whether a package is installed: #!/usr/bin/env bashrun_install(){ ## Prompt the user read -p "Do you want to install missing libraries? [Y/n]: " answer ## Set the default value if no answer was given answer=${answer:Y} ## If the answer matches y or Y, install [[ $answer =~ [Yy] ]] && apt-get install ${boostlibnames[@]}}boostlibnames=("libboost-serialization1.55.0" "libboost-thread1.55.0" "libboost-date-time1.55.0" "libboost-signals1.55.0" "nedit")## Run the run_install function if sany of the libraries are missingdpkg -s "${boostlibnames[@]}" >/dev/null 2>&1 || run_install
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235605", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/27719/" ] }
235,606
How can I subtract two dates in epoch format using Shell Scripting.I want the output in Months, Days, Hours format.Also It should work even for more than 12 months ( as I came across few which were resetting to 0 months if more than 12)
Try something like this: #!/bin/bashd1=`date -d 20140929 +%s`d2=`date -d 20001115 +%s`date --date=@$(($d1 - $d2)) +'%m months, %d days, %H hours' Output: 11 months, 15 days, 02 hours
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235606", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/137613/" ] }
235,671
I have a bash script that reads filenames, takes a selection of data, build a table, and then adds the header. Unfortunately, at the point to add the header and give the output file, I have the following error message: ./big_table_rcp.sh: line 153: /tmp/out: Permission denied It is linked with the following line: | cat - out_${scenario}.txt > /tmp/out && mv /tmp/out ${gauge}_${scenario}.txt Does anyone know how to give access to the output file?
You may be getting permission errors because you don't have permissions to access /tmp/out or the /tmp directory. Before the offending line, include somehting like ls -l /tmp | grep out to see what permissions the /tmp/out file has. In addition, instead of using /tmp/out , use mktemp . tmpfile=`mktemp`your code here | cat - out_${scenario}.txt > "$tmpfile" && mv "$tmpfile" ${gauge}_${scenario}.txt From man mktemp : Create a temporary file or directory, safely, and print its name.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235671", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/125347/" ] }
235,704
I have fish installed in my Linux Mint DE. I really like how fish makes things easier and it looks so pretty although I haven't find a correct answer about why I can't execute: sudo: !!: command not found At first I tried to escape the exclamation signs with sudo !! but didn't work either. Does someone know why is this failing?
I haven't found a inbuilt replacement for !! in Fish however you can write a function that allows you to keep using !! Taken from this answer https://superuser.com/a/719538/226822 function sudo --description "Replacement for Bash 'sudo !!' command to run last command using sudo." if test "$argv" = !! echo sudo $history[1] eval command sudo $history[1] else command sudo $argv endend
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235704", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/91570/" ] }
235,830
So I can use this netcat command to check if a UDP port is open: $ nc -vz -u 10.1.0.100 53Connection to 10.1.0.100 53 port [udp/domain] succeeded! Unlike TCP, UDP is connectionless (fire and forget). So at a high level does anyone know how netcat knows the UDP port is open? Does it ask for a reply or something like that?
Judging by the specific output Connection to Connection to 10.1.0.100 53 port [udp/domain] succeeded! you are using openbsd-netcat. Looking at the code for that the test is to bind to the UDP socket, i.e. there is an open connection: if (vflag || zflag) { /* For UDP, make sure we are connected. */ if (uflag) { if (udptest(s) == -1) { ret = 1; continue; } } /* Don't look up port if -n. */ if (nflag) sv = NULL; else { sv = getservbyport( ntohs(atoi(portlist[i])), uflag ? "udp" : "tcp"); } fprintf(stderr, "Connection to %s %s port [%s/%s] " "succeeded!\n", host, portlist[i], uflag ? "udp" : "tcp", sv ? sv->s_name : "*"); udptest issues around 3 writes to the open socket. There is a note that this doesn't work for IPv6 and fails after around 100 ports checked. So while the other suggestion may be valid, I don't think that's happening in this particular case.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235830", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/82075/" ] }
235,831
When trying to redirect program output with the "some number greater than" syntax (eg foo 2> myfile ), what are the possible numbers here and what do they represent? I believe 1 is /dev/stdout , 2 is /dev/stderr . What about 5 & 6? Is there 3, 4 or some number greater than 6?
This supposed program will write to file descriptor number you specified.consider the following hello world program: #include <stdio.h>main(){ ssize_t i = 0 ; printf ("hello world\n") ; i = write( 5 , "Bonjour Monde\n", 14 ) ; printf ("%d octet dans 5\n", (int) i) ;} compile it me@mybox:~/tmp7$ make hwcc hw.c -o hw now a simple run me@mybox:~/tmp7$ ./hwhello world-1 octet dans 5 no file for 5, so no byte wrote. next try: me@mybox:~/tmp7$ ./hw 5> uhello world14 octet dans 5me@mybox:~/tmp7$ cat uBonjour Monde I manage to get an output while specifying a file and a file descriptor (e.g. 5>u ). In practice, unless you have wrote such funny program as above, you are unlikely to collect data using 5>foo . in shell script, construct using <( ) are more usefull: diff <( cmd -par 1 ) <(cmd -par 2)
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235831", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/86960/" ] }
235,886
# lsof -n -itcp | wc 92 919 10212# lsof -n | grep TCP | wc 2482 27222 373861 What I'm doing wrong with lsof -itcp ? Such calling is skipping part of connections, looks like this are connections of threads.
The correct syntax is: lsof -a -i4 -i6 -itcp This selects TCP sockets that are IPv4 or IPv6.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235886", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138347/" ] }
235,891
I am trying to install tomcat on a new CentOS 7 virtual machine. I successfully installed apache httpd, and am able to get the apache test page when I type the ip of the virtual machine into a web browser on another computer in the network. But I am getting the following error message when I type systemctl start tomcat : Job for tomcat.service failed. See 'systemctl status tomcat.service' and 'journalctl -xn' for details. Here is the complete history of commands in the install of java and tomcat: I first started by installing java using the instructions from this tutorial because the tomcat instructions (second block below) wanted me to use openjdk, and I need to use real java: //Install Java# cd /opt/# yum install wget# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u60-b27/jdk-8u60-linux-x64.tar.gz"# tar xzf jdk-8u60-linux-x64.tar.gz# cd /opt/jdk1.8.0_60/# alternatives --install /usr/bin/java java /opt/jdk1.8.0_60/bin/java 2# alternatives --config java(Select the version you want)# alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_60/bin/jar 2# alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_60/bin/javac 2# alternatives --set jar /opt/jdk1.8.0_60/bin/jar# alternatives --set javac /opt/jdk1.8.0_60/bin/javac# java -version (checks to see you install correct version)# export JAVA_HOME=/opt/jdk1.8.0_60# export JRE_HOME=/opt/jdk1.8.0_60/jre# export PATH=$PATH:/opt/jdk1.8.0_60/bin:/opt/jdk1.8.0_60/jre/bin Note that the preceding tutorial does not explain how to put the environment variables in /etc/environment , so I stopped before that command. The following commands are from this other tutorial . I started at the point after installing java: //Install TomcatLogin as sudo user, not root.# sudo groupadd tomcat# sudo useradd -M -s /bin/nologin -g tomcat -d /opt/tomcat tomcat# cd ~# wget http://mirrors.gigenet.com/apache/tomcat/tomcat-8/v8.0.27/bin/apache-tomcat-8.0.27.tar.gz# sudo mkdir /opt/tomcat# sudo tar xvf apache-tomcat-8*tar.gz -C /opt/tomcat --strip-components=1# cd /opt/tomcat# sudo chgrp -R tomcat conf# sudo chmod g+rwx conf# sudo chmod g+r conf/*# sudo chown -R tomcat work/ temp/ logs/# sudo vi /etc/systemd/system/tomcat.serviceCut and paste the following file contents:################################################### Systemd unit file for tomcat[Unit]Description=Apache Tomcat Web Application ContainerAfter=syslog.target network.target[Service]Type=forkingEnvironment=JAVA_HOME=/usr/lib/jvm/jreEnvironment=CATALINA_PID=/opt/tomcat/temp/tomcat.pidEnvironment=CATALINA_HOME=/opt/tomcatEnvironment=CATALINA_BASE=/opt/tomcatEnvironment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'ExecStart=/opt/tomcat/bin/startup.shExecStop=/bin/kill -15 $MAINPIDUser=tomcatGroup=tomcat[Install]WantedBy=multi-user.target################################################### sudo systemctl daemon-reload# sudo systemctl start tomcatJob for tomcat.service failed. See 'systemctl status tomcat.service' and 'journalctl -xn' for details.# sudo systemctl start tomcat.service Job for tomcat.service failed. See 'systemctl status tomcat.service' and 'journalctl -xn' for details. # sudo systemctl enable tomcat.serviceln -s '/etc/systemd/system/tomcat.service' '/etc/systemd/system/multi-user.target.wants/tomcat.service' # sudo systemctl enable tomcat # sudo systemctl status tomcat.servicetomcat.service - Apache Tomcat Web Application Container Loaded: loaded (/etc/systemd/system/tomcat.service; enabled) Active: failed (Result: exit-code) since Tue 2015-10-13 11:05:31 PDT; 47s agoOct 13 11:05:31 localhost.localdomain kill[20887]: -q, --queue <sig> use sigqueue(2) rather than kill(2)Oct 13 11:05:31 localhost.localdomain kill[20887]: -p, --pid print pids without signaling themOct 13 11:05:31 localhost.localdomain kill[20887]: -l, --list [=<signal>] list signal names, or convert one to a nameOct 13 11:05:31 localhost.localdomain kill[20887]: -L, --table list signal names and numbersOct 13 11:05:31 localhost.localdomain kill[20887]: -h, --help display this help and exitOct 13 11:05:31 localhost.localdomain kill[20887]: -V, --version output version information and exitOct 13 11:05:31 localhost.localdomain kill[20887]: For more details see kill(1).Oct 13 11:05:31 localhost.localdomain systemd[1]: tomcat.service: control process exited, code=exited status=1Oct 13 11:05:31 localhost.localdomain systemd[1]: Failed to start Apache Tomcat Web Application Container.Oct 13 11:05:31 localhost.localdomain systemd[1]: Unit tomcat.service entered failed state. Doing a yum localinstall of an updated jdk rpm, as suggested in this other posting , did not work. EDITS: As per @Bram's suggestion, I changed the config file to the following, but am still getting the same error: # Systemd unit file for tomcat[Unit]Description=Apache Tomcat Web Application ContainerAfter=syslog.target network.target[Service]Type=forkingEnvironment=JAVA_HOME=/opt/jdk1.8.0_60Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pidEnvironment=CATALINA_HOME=/opt/tomcatEnvironment=CATALINA_BASE=/opt/tomcatEnvironment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'ExecStart=/opt/tomcat/bin/startup.shExecStop=/bin/kill -15 $MAINPIDUser=tomcatGroup=tomcat[Install]WantedBy=multi-user.target Also, as per @JeffSchaller's comment in chat, I was able to get tomcat to start natively as follows: [user@localhost tomcat]$ sudo /opt/tomcat/bin/startup.shUsing CATALINA_BASE: /opt/tomcatUsing CATALINA_HOME: /opt/tomcatUsing CATALINA_TMPDIR: /opt/tomcat/tempUsing JRE_HOME: /Using CLASSPATH: /opt/tomcat/bin/bootstrap.jar:/opt/tomcat/bin/tomcat-juli.jarTomcat started.[user@localhost tomcat]$ Thus the problem in this OP seems to be with the systemd config. How can I fix it?
I had the same problem, fixed it by: giving tomcat user ownership of the whole tomcat directory: cd /opt && sudo chown -R tomcat tomcat/ and commenting out below line in /etc/systemd/system/tomcat.service: Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235891", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/92670/" ] }
235,985
I've read that redirecting output to a fixed name file in /tmp can be a security risk, because if an attacker (or malcontent) notices that a file /tmp/tmpfileformyscript.tmp is created when I run my script (even if he doesn't have read access to my script), he can for example make a symlink ln -s ~wildcard/.bashrc /tmp/tmpfileformyscript.tmp which will cause me to destroy my .bashrc file when I run my script. So instead I can use something like filename="tmpfile.tmp.$RANDOM" ; echo outputtext > "$filename" . However, I'd like to use a tmp file for caching sometimes, in which case I would want to know if "tmpfile.tmp.*" matches anything in /tmp and if so, use that file rather than creating a new one. Unfortunately test and the equivalent [ -f filename ] doesn't support file globbing as far as I can tell. Thus my question is twofold: How can I safely create a tempfile? Is "predictablename.$RANDOM" an acceptable practice or is there a better (more secure, easier) way? How can I easily access the file and/or establish its existence later by checking for predictablename ?
Use the mktemp utility to create a temporary file with an unpredictable name. It isn't standardized by POSIX, but it's available on *BSD as well as Linux. > /tmp/predictable.$RANDOM is not a good choice because it's mostly predictable¹, which opens your script to an attack where the attacker can trick your script into overwriting a file you have write access to, or giving them access to the temporary file. This is an insecure temporary file vulnerability. mktemp doesn't have this vulnerability because creates the file safely (it won't overwrite an existing file, even if symbolic links are involved) and uses a sufficiently unpredictable name to avoid a denial of service. If creating one temporary file and working with it is not good enough, create a temporary directory with mktemp -d , and work in there. mktemp also takes care to use $TMPDIR if the variable is set, falling back to /tmp if it's unset. More and more distributions set up TMPDIR to be a private directory, e.g. /run/1234/tmp where 1234 is your UID. This eliminates the risk of temporary file vulnerabilities, at the cost of no longer being able to share temporary files between users (which is occasionally useful, but not very often; /tmp is still available, just not TMPDIR ). If you need a reproducible file name, then create a file with a well-defined name (with no random component) under the user's home directory. The modern convention is the XDG user directory specification . If the file could be removed without causing data loss, use the XDG_CACHE_HOME environment variable, defaulting to ~/.cache . You should probably create a subdirectory named after your application and work in there. CACHE_DIR="${XDG_CACHE_HOME:-"$HOME/.cache"}"/Wildcard-scripts[ -d "$CACHE_DIR" ] || mkdir -p -- "$CACHE_DIR"CACHE_FILE="$CACHE_DIR/tmpfileformyscript" ¹ Not only does $RANDOM only takes 32767 possible values, but it's easy to predict without even trying many values. Bash's random number generator is a LCG seeded by the PID and time of first use. Zsh's is the platform's rand seeded by startup time. ATT Ksh's is the platform's rand seeded by PID. Mksh's is an LCG with a more complex, but still not security-quality seed. All of them can be predicted by another process with a fairly large chance of success.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/235985", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/135943/" ] }
235,995
I am looking for a way so that a particular user or a group should not given the permission to remove any file in the system, but only read/execute the file.
There are some users on my system who don't know anything about the PC, so they try to explore it for just learning purpose. My intention is that I can give them a separate account by which they can explore the system without accidently removing or changing any file on the system, but I as another user should be able to do any changes on the system. That is the roughly way a Unix/Linux system normally works. A user only has the right to delete or modify (a) files or directories that he owns or (b) files or directories for which a group that he is in has write permission. The system administrator (that's you, I presume) has control over everything. So, just make sure that these new users are in their own individual group. Unix was designed to be a multi-user system. So, from the start, Unix/Linux give normal users only only limited permissions. Generally, no normal user can mess with system files. Only the system administrator, called root , can do that. Some systems allow normal users to get root's capabilities by running sudo . Make sure that your /etc/sudoers file does not give that capability to them. If you want to be severe, do not give them ownership even of a home directory. They would still have write permission to /tmp and /var/tmp but that shouldn't cause trouble unless they create files so big that they fill up the partition.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/235995", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/124146/" ] }
236,009
Consider the following command: watch -d "ps -ef | grep java" It gives following output: kshitiz 11369 11285 0 Oct13 ? 00:06:02 /usr/lib/jvm/jdk1.7.0_40/jre/bin/java -Djava.awt.headless=true -Didea.version==14.1.2 -Xmx512m -Dfile.e The output beyond -Dfile.e is truncated or flows off screen. How can I scroll to see the output or word wrap it? Using fold without watch: Using fold with watch:
Pipe the output to fold to wrap the output at a specified width (defaultly 80): watch -d "ps -efww | grep '[j]ava' | fold -s" Use the -w flag of ps for wide output, and twice for unlimited output. fold -s breaks at spaces. Also notice the grep command. I changed java to [j]ava . Thisway the grep process will not match himself in the ps output.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236009", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/19506/" ] }
236,028
I have a program here, that depends on the output of netstat . More concrete: netstat -apn . Here is an example of a normal output. Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program nametcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN - A client of mine has some other output (as an example): Proto Recv-Q Send-Q Endereço Local Endereço Remoto Estado PID/Program nametcp 0 0 0.0.0.0:111 0.0.0.0:* OUÇA - I want to test my software with a changed output of netstat , like the output of the client. So the question is: What should I do to change the output language of netstat , so I can reproduce the errors, the client gets? I already tried to change the language with export LANG=pt_PT , but the output didn't change.
First you need to make sure that your machine has the necessary locale set up. You can see available locales with locale -a . For example, on my system: $ locale -aCC.UTF-8el_GR.utf8en_US.utf8fr_FR.utf8POSIX As you can see above, I don't have the Portuguese locale. On my Debian, I can create it by running sudo dpkg-reconfigure locales , and choosing the relevant locale: Package configuration ┌──────────────────────────┤ Configuring locales ├──────────────────────────┐ │ Locales are a framework to switch between multiple languages and allow │ │ users to use their language, country, characters, collation order, etc. │ │ │ │ Please choose which locales to generate. UTF-8 locales should be chosen │ │ by default, particularly for new installations. Other character sets may │ │ be useful for backwards compatibility with older systems and software. │ │ │ │ Locales to be generated: │ │ │ │ [ ] pt_BR.UTF-8 UTF-8 ↑ │ │ [ ] pt_PT ISO-8859-1 ▒ │ │ [*] pt_PT.UTF-8 UTF-8 ▮ │ │ [ ] pt_PT@euro ISO-8859-15 ▒ │ │ [ ] quz_PE UTF-8 ↓ │ │ │ │ │ │ <Ok> <Cancel> │ │ │ └───────────────────────────────────────────────────────────────────────────┘ After hitting Enter , you should get: $ sudo dpkg-reconfigure localesGenerating locales (this might take a while)... el_GR.UTF-8... done en_US.UTF-8... done fr_FR.UTF-8... done pt_PT.UTF-8... doneGeneration complete. If you are not using a Debian-based distribution, you will need to do this manually: Add the relevant locale name to /etc/locale.gen . For example: pt_PT.UTF-8 UTF-8 Run locale-gen After the above steps (either the manual approach or the dpkg-reconfigre locales one), locale -a will also list the Portuguese locale: $ locale -aCC.UTF-8el_GR.utf8en_US.utf8fr_FR.utf8POSIXpt_PT.utf8 Now, you can choose what language output is displayed in: $ LC_ALL=el_GR.utf8 dateΤετ 14 Οκτ 2015 12:34:28 μμ EEST$ LC_ALL=fr_FR.utf8 datemercredi 14 octobre 2015, 12:35:07 (UTC+0300)$ LC_ALL=pt_PT.utf8 dateQua Out 14 12:35:11 EEST 2015 However, whether or not a particular program is capable of printing output in the selected locale will depend on whether it has been translated; on whether the package ships with the relevant .mo translation file. In the case of netstat , this is /usr/share/locale/${LANG%_*}/LC_MESSAGES/net-tools.mo . On my Debian, the French locale has it but the Portuguese one does not: $ ls /usr/share/locale/{fr,pt}/LC_MESSAGES/net*ls: cannot access /usr/share/locale/pt/LC_MESSAGES/net*: No such file or directory/usr/share/locale/fr/LC_MESSAGES/net-tools.mo This is why I can run netstat in French: $ LC_ALL=fr_FR.utf8 netstat -apn | head -n2(Tous les processus ne peuvent être identifiés, les infos sur les processusnon possédés ne seront pas affichées, vous devez être root pour les voir toutes.)Connexions Internet actives (serveurs et établies)Proto Recv-Q Send-Q Adresse locale Adresse distante Etat PID/Program name But not in Portuguese: $ LC_ALL=pt_PT.utf8 netstat -apn | head -n2(Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.)Active Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236028", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/116283/" ] }
236,029
I want to write a script to return just the extension of the input file name. For example, textfile.txt should return txt . I'm new to Linux and bash, and I'm trying to learn how to write basic scripts. Thanks!
The shell, bash for example, has many string manipulation features. One of them lets you remove everything up to a given pattern: ${VAR##GLOB} The syntax above removes everything from the variable $VAR until the first match of the glob GLOB . So, to print a file's extension without its name, you could do: $ file="file.txt"$ echo ${file##*.}txt Note that this can also deal with more than one "extension": $ file="file.new.txt"$ echo ${file##*.}txt If you don't want that, use one # instead, which will remove the shortest match instead of the longest: $ echo ${file#*.}new.txt Now, to run this on all files in a directory, you could do: $ ls file.avi file.pdf file.png file.txt$ for file in *; do echo "$file : ${file##*.}"; donefile.avi : avifile.pdf : pdffile.png : pngfile.txt : txt And, for the sake of completeness, you can also get the file name without its extension using ${file%.*} : $ for file in *; do echo "$file : ${file##*.} : ${file%.*}"; donefile.avi : avi : filefile.pdf : pdf : filefile.png : png : filefile.txt : txt : file
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/236029", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138438/" ] }
236,084
I'm using CentOS 7 what my aim is to create a cron for every five seconds but as I researched we can use cron only for a minute so what I am doing now is I have created a shell file. hit.sh while sleep 5; do curl http://localhost/test.php; done but I have hit it manually through right clicking it. What I want is to create a service for that file so that i can start and stop it automatically. I found the script to create a service #!/bin/bash# chkconfig: 2345 20 80# description: Description comes here....# Source function library.. /etc/init.d/functionsstart() { # code to start app comes here # example: daemon program_name &}stop() { # code to stop app comes here # example: killproc program_name}case "$1" in start) start ;; stop) stop ;; restart) stop start ;; status) # code to check status of app comes here # example: status program_name ;; *) echo "Usage: $0 {start|stop|status|restart}"esacexit 0 But I don't know what to write in start or stop methods I tried placing the same content of hit.sh in start(){} but it gave error for } in stop method.
Users trying to run a script as a daemon on a modern system should be using systemd : [Unit]Description=hit serviceAfter=network-online.target[Service]ExecStart=/path/to/hit.sh[Install]WantedBy=multi-user.target Save this as /etc/systemd/system/hit.service , and then you will be able to start/stop/enable/disable it with systemctl start hit , etc. Old answer from 2015: If you'd like to reuse your code sample, it could look something like: #!/bin/bashcase "$1" in start) /path/to/hit.sh & echo $!>/var/run/hit.pid ;;stop) kill `cat /var/run/hit.pid` rm /var/run/hit.pid ;;restart) $0 stop $0 start ;;status) if [ -e /var/run/hit.pid ]; then echo hit.sh is running, pid=`cat /var/run/hit.pid` else echo hit.sh is NOT running exit 1 fi ;;*) echo "Usage: $0 {start|stop|status|restart}"esacexit 0 Naturally, the script you want to be executed as a service should go to e.g. /usr/local/bin/hit.sh , and the above code should go to /etc/init.d/hitservice . For each runlevel which needs this service running, you will need to create a respective symlink. For example, a symlink named /etc/init.d/rc5.d/S99hitservice will start the service for runlevel 5. Of course, you can still start and stop it manually via service hitservice start / service hitservice stop
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/236084", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/131129/" ] }
236,094
Sure there's a super simple smart way to do this, but since history in zshell seems to be aliased to fc, there's no way to use the tricks mentioned in How to remove a single line from history? . Any pointers on how to do this? My use case would be to remove the last issued command from history so it stops autocompleting (mostly when you've mistyped something and it keeps showing up). I know I can get the last issued command by doing history | tail -n 1 , but history -d doesn't work and I can't find proper documentation for zsh.
Zsh doesn't offer a real history edition facility. The command history is basically read-only. All you can do is replace it wholesale. To edit the command line history: Save it to a file: fc -W Edit the file Load the history from the file: fc -R You can choose the file name by setting HISTFILE . Untested code: remove_last_history_entry () { setopt local_options extended_history no_hist_save_no_dups err_return local HISTFILE=~/.zsh_history_tmp_$$ SAVEHIST=$HISTSIZE fc -W ed -s $HISTFILE <<EOF >/dev/nulldwqEOF fc -R}
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236094", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138477/" ] }
236,103
I want to use cat with wildcards in bash in order to print multiple small files (every file is one sentence) to standard output. However, the separate file contents are not separated by a newline, which I'd like to for ease of reading. How can I add a file delimiter of some sort to this command?
Define a shell function which outputs an end of line after every file and use it instead of cat : endlcat() { for file in "$@"; do cat -- "$file" echo done} then you can use endlcat * . The for loop loops over all provided arguments ( $@ ) which are already escaped by the shell when you use wildcards like * . The -- is required to not choke on file names starting with a dash. Finally the echo outputs a newline.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/236103", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/114955/" ] }
236,107
When setting "set -x" inside bash script, or if you run your script with bash -x , you will get all the arguments printed to the screen together with the stdout. Is it possible to have stderr and stdout printed to screen but redirecting the set -x output to the log file without having it printed to the screen? The idea is to have all the info I can get inside the log, but only print regular stdout and stderr to the screen.
user1@mac1:~/tmp$ cat t1.shexec 4>shell.logBASH_XTRACEFD=4set -xecho abccat ffffuser1@mac1:~/tmp$ bash t1.shabccat: ffff: No such file or directoryuser1@mac1:~/tmp$ cat shell.log+ echo abc+ cat ffffuser1@mac1:~/tmp$
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236107", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/55603/" ] }
236,116
I am using zsh and oh-my-zsh on Ubuntu. To change into the recent directory in the past there was an alias set to - which is the same as cd - . Somehow the alias disappeared at my machine. This might have happened due to updates I pulled from the oh-my-zsh repository. Now, I would like to add this alias to my own dotfiles. How can I do this?
The alias was removed in this commit . To add it back: alias -- -='cd -' Most of POSIX shells need -- for this alias work, only dash doesn't: $ dash$ alias -='echo 1'$ -1
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236116", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/15156/" ] }
236,127
I have to disable some event to avoid an immediate wakeup after suspend in my desktop machine, and I made it by trial and error (works well, so that is not a problem). But I wonder... for example in my laptop I have a long list in /proc/acpi/wakeup : [...]RP03 S4 *disabledPXSX S4 *disabledRP04 S4 *disabled pci:0000:00:1c.3PXSX S4 *enabled pci:0000:03:00.0RP06 S4 *disabled[...] I have searched around and I can't find a place where a list with the meaning of the 4-letter code in the first column is explained. I imagine that the events with a device name after them are linked/generated by that device, but I am at a loss with most of the rest... minus wild guesses. How can I know what, for example, event RP06 is? Is there anywhere a list? Or are that codes vendor-specific?
The codes come from the DSDT (Differentiated System Description Table) of your BIOS.This "table" describes the integrated devices on your mainboard, their dependencies and power-management functions. Devices in the DSDT are arranged in a tree and each path component is limited to 4 characters. The codes in /proc/acpi/wakeup are the last path components (aka the names) of the devices the vendor used for the devices. They are inherently vendor-specific, as the vendor may name any device as he likes. But there are some names that are common between many vendors, either because they are used as examples in the ACPI specification or because they are obvious abbreviations: PS2K: PS/2 keyboard PS2M: PS/2 mouse PWRB or PBTN: Power button SLPB: Sleep button LID: Laptop lid RP0x or EXPx: PCIE slot #x (aka PCI Express Root Port #x) EHCx or USBx: USB 2.0 (EHCI) chip XHC: USB 3.0 (XHCI) chip PEGx: PCI Express for Graphics slot #x GLAN or IGBE: Gigabit Ethernet
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/236127", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/52205/" ] }
236,128
I have these variant of urls RewriteRule ^/trendy/the-reason-for-example/? http://www.example.com/trendy/the-reason [NC, L, R=301]RewriteRule ^/lol/2015/10..._for-example http://www.example.com/lol/the-reason [NC, L, R=301]RewriteRule ^/sports/this-one***-as-well/ http://www.example.com/sports/this-one [NC, L, R=301]RewriteRule ^/buzz/the-#reason-for-buzz http://www.example.com/buzz/buzz-sells [NC, L, R=301]RewriteRule ^/omg/ what-the-hell http://www.example.com/omg/wthell [NC, L, R=301]RewriteRule ^/hash/HELL-YEAH http://www.example.com/hash/oh-yes [NC, L, R=301]RewriteRule ^/celeb/he-did-it! http://www.example.com/celeb/we-believe [NC, L, R=301] and I want to edit them using awk (sed or any other tool) to help edit these variant of URLs so it passes apache's rewriterule config test Notice the characters like (*), (.), (#), (!) and even the space on the 5th lineHow do I edit these set of lines so that everything looks correct to be deployed to apache and pass apache config test httpd -t ? EDIT: v1 Here is something that I am looking for that will pass apache's test RewriteRule ^/trendy/the-reason-for-example/? http://www.example.com/trendy/the-reason [NC, L, R=301]RewriteRule ^/lol/2015/10\.\.\._for-example http://www.example.com/lol/the-reason [NC, L, R=301]RewriteRule ^/sports/this-one\*\*\*-as-well/ http://www.example.com/sports/this-one [NC, L, R=301]RewriteRule ^/buzz/the-\#reason-for-buzz http://www.example.com/buzz/buzz-sells [NC, L, R=301]RewriteRule ^/omg/\ what-the-hell http://www.example.com/omg/wthell [NC, L, R=301]RewriteRule ^/hash/HELL-YEAH http://www.example.com/hash/oh-yes [NC, L, R=301]RewriteRule ^/celeb/he-did-it\! http://www.example.com/celeb/we-believe [NC, L, R=301] NOTE: please note line 5 had space and I had to escape the space. So there needs to be a way to detect is there is space in column 2 then escape it -- something along that line.
The codes come from the DSDT (Differentiated System Description Table) of your BIOS.This "table" describes the integrated devices on your mainboard, their dependencies and power-management functions. Devices in the DSDT are arranged in a tree and each path component is limited to 4 characters. The codes in /proc/acpi/wakeup are the last path components (aka the names) of the devices the vendor used for the devices. They are inherently vendor-specific, as the vendor may name any device as he likes. But there are some names that are common between many vendors, either because they are used as examples in the ACPI specification or because they are obvious abbreviations: PS2K: PS/2 keyboard PS2M: PS/2 mouse PWRB or PBTN: Power button SLPB: Sleep button LID: Laptop lid RP0x or EXPx: PCIE slot #x (aka PCI Express Root Port #x) EHCx or USBx: USB 2.0 (EHCI) chip XHC: USB 3.0 (XHCI) chip PEGx: PCI Express for Graphics slot #x GLAN or IGBE: Gigabit Ethernet
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/236128", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138406/" ] }
236,147
The path is as follows: /usr/lib64/qt3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin:/home/mj1210/.local/bin:/home/mj1210/bin
The codes come from the DSDT (Differentiated System Description Table) of your BIOS.This "table" describes the integrated devices on your mainboard, their dependencies and power-management functions. Devices in the DSDT are arranged in a tree and each path component is limited to 4 characters. The codes in /proc/acpi/wakeup are the last path components (aka the names) of the devices the vendor used for the devices. They are inherently vendor-specific, as the vendor may name any device as he likes. But there are some names that are common between many vendors, either because they are used as examples in the ACPI specification or because they are obvious abbreviations: PS2K: PS/2 keyboard PS2M: PS/2 mouse PWRB or PBTN: Power button SLPB: Sleep button LID: Laptop lid RP0x or EXPx: PCIE slot #x (aka PCI Express Root Port #x) EHCx or USBx: USB 2.0 (EHCI) chip XHC: USB 3.0 (XHCI) chip PEGx: PCI Express for Graphics slot #x GLAN or IGBE: Gigabit Ethernet
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/236147", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138498/" ] }
236,154
I have a input text file with 10 columns, while processing this file, in one of the middle column, I am getting this type of data.I required column value to be as below: Input Column value: "This is my new program:"Hello World"" Required Column value: "This is my new program: Hello World". Please help me in any Unix shell scripts or any commands.Really appreciate your time and thanks in advance.
A very simple option is to use sed as @Dani proposes if you want to remove all double-quotes. $ echo "This is my program \"Hello World\"" | sed 's/"//g'This is my program Hello World Nevertheless, if you want to remove only internal quotes, I would suggest removing all quotes and adding one at the beginning and one at the end as follows. Let's say we have a file sample.txt with these contents: $ cat sample.txt"This is the "First" Line""This is the "Second" Line""This is the "Third" Line" Then, if you want to remove only internal quotes, I would suggest the following: $ cat sample.txt | sed 's/"//g' | sed 's/^/"/' |sed 's/$/"/'"This is the First Line""This is the Second Line""This is the Third Line" Explanation: sed 's/"//g' removes all double quotes on each line sed 's/^/"/' adds a double-quote at the beginning of each line sed 's/$/"/' adds a double-quote at the end of each line sed 's/|/"|"/g' adds a quote before and after each pipe. Hope this helps. EDIT : As per the pipe separator comment, we have to slightly change the command Let sample.txt be: $ cat sample.txt"This is the "First" column"|"This is the "Second" column"|"This is the "Third" column" Then, adding a replacer command for the pipe give us the final solution. $ cat sample.txt | sed 's/"//g' | sed 's/^/"/' |sed 's/$/"/' | sed 's/|/"|"/g'"This is the First column"|"This is the Second column"|"This is the Third column" The script option Using this sample.txt file $ cat sample.txt"This is the "first" column"|12345|"This is the "second" column"|67890|"This is the "third" column" And this script #!/bin/kshcounter=1column="initialized"result=""while [[ "$column" != "" ]]do eval "column=$(cat sample.txt | cut -d"|" -f$counter)" eval "text=$(cat sample.txt | cut -d"|" -f$counter | grep '"')" if [[ "$column" = "$text" && -n "$column" ]] then if [[ "$result" = "" ]] then result="_2quotehere_${column}_2quotehere_" else result="${result}|_2quotehere_${column}_2quotehere_" fi else if [[ -n "$column" ]] then if [[ "$result" = "" ]] then result="${column}" else result="${result}|${column}" fi fi fi echo $result | sed 's/_2quotehere_/"/g' > output.txt (( counter+=1 ))donecat output.txtexit 0 You will get this: $ ./process.sh"This is the first column"|12345|"This is the second column"|67890|"This is the third column"$ cat output.txt"This is the first column"|12345|"This is the second column"|67890|"This is the third column" I hope this is the processing you need. Let me know! FINAL EDIT This script processes the input line you provided, several times included. Only restriction is that all 20 columns MUST BE on the same line. #!/bin/kshrm output.txt > /dev/null 2>&1column="initialized"result=""lineCounter=1while read linedo print "LINE $lineCounter: $line" counter=1 while [[ ${counter} -le 20 ]] do eval 'column=$(print ${line} | cut -d"|" -f$counter)' eval 'text=$(print ${line} | cut -d"|" -f$counter | grep \")' print "LINE ${lineCounter} COLUMN ${counter}: $column" if [[ "$column" = "$text" && -n ${column} ]] then if [[ "$result" = "" ]] then result="_2quotehere_$(echo ${column} | sed 's/\"//g')_2quotehere_" else result="${result}|_2quotehere_$( echo ${column} | sed 's/\"//g')_2quotehere_" fi else if [[ "$result" = "" ]] then result=${column} else result="${result}|${column}" fi fi (( counter+=1 )) done (( lineCounter+=1 )) echo -e $result | sed 's/_2quotehere_/"/g' >> output.txt result=""done < input.txtprint "OUTPUT CONTENTS:"cat output.txtexit 0 From here, you must be able to get it working for your particular case.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/236154", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/130549/" ] }
236,164
I have thousands of files named 1.txt 2.txt and so on. Some of those files are missing. Which would be the easiest way to find out which files are missing?
ub=1000 # Replace this with the largest existing file's number.seq "$ub" | while read -r i; do [[ -f "$i.txt" ]] || echo "$i.txt is missing"done You can easily find the proper value for ub by doing ls | sort -n or similar. This relies on the files being in the format output by seq , notably here without leading zeroes.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236164", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138519/" ] }
236,252
I tried with gparted, it didn't work. I found a SDFormatter , tool for windows that did the full erase. I have a SD card and want to install Debian onto it. The dd process takes about 45 minutes, after that I quit it. In my Windows machine, it shows up in drive list but there's also an undefined error while try formatting or even opening. gparted just tells me /dev/mmcblk0: unrecognised disk label I issued dd if='deb.iso' of=/dev/mmcblk0 bs=512kdd: error writing „/dev/mmcblk0“: I/O error0+1 data in0+0 data outcopied 0 Bytes (0 B), 10,098 s, 0,0 kB/s After that I tried root@kali:~# lsblk -o NAME,FSTYPE,MOUNTPOINT,SIZE,RONAME FSTYPE MOUNTPOINT SIZE ROsda 465,8G 0├─sda1 ext4 / 450,1G 0├─sda2 1K 0└─sda5 swap [SWAP] 15,7G 0sr0 1024M 0mmcblk0 29,5G 0 mmcblk0 is the one i have problems with . Last,I tried root@kali:~# mkdosfs -F 32 -v /dev/mmcblk0mkfs.fat 3.0.26 (2014-03-07)/dev/mmcblk0 has 4 heads and 16 sectors per track,hidden sectors 0x0000;logical sector size is 512,using 0xf8 media descriptor, with 61896704 sectors;drive number 0x80;filesystem has 2 32-bit FATs and 32 sectors per cluster.FAT size is 15105 sectors, and provides 1933326 clusters.There are 32 reserved sectors.Volume ID is 2df52746, no volume label.mkdosfs: failed whilst writing reserved sector I have absolutely no idea why it won't work.
dd: error writing „/dev/mmcblk0“: I/O error “I/O error” (short for “input/output error”) means that there was a problem accessing a hardware. When you get this on a storage medium, it means that your storage medium is dead or dying, or you have a loose wire or underpowered peripheral or some other hardware problem. I/O error from an SD card means that it's dead. That's why no software lets you format it. The card isn't able to store data any more. Some of its area might still be usable, but it's missing some of the bits. Given the quality of card readers, it's possible that your card reader is broken and the card would work on another reader. But that's a rarer scenario, don't count on it. You can't fix an SD card. Throw the SD card away and use a working one.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236252", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138569/" ] }
236,254
watch is great for monitoring events on a polling basis. However I'm looking for a utility that's similar, except event-driven (i.e. monitoring every change to a file in /sys/kernel/debug/my_node). Is there already such a utility?
dd: error writing „/dev/mmcblk0“: I/O error “I/O error” (short for “input/output error”) means that there was a problem accessing a hardware. When you get this on a storage medium, it means that your storage medium is dead or dying, or you have a loose wire or underpowered peripheral or some other hardware problem. I/O error from an SD card means that it's dead. That's why no software lets you format it. The card isn't able to store data any more. Some of its area might still be usable, but it's missing some of the bits. Given the quality of card readers, it's possible that your card reader is broken and the card would work on another reader. But that's a rarer scenario, don't count on it. You can't fix an SD card. Throw the SD card away and use a working one.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236254", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/34275/" ] }
236,256
I've google'd around to no avail. I recently installed Linux Mint and in doing so I set up my wireless network at home, which works fine when I'm there. However, I'm now trying to connect to another WiFi, all the available nearby WiFi connections pop up fine, I click connect (there's no option for settings or anything) and it attempts to connect indefinitely, It seems to get stuck in a forever-loading connection symbol and never prompts me for a password or anything. I haven't managed to find anyone with a similar problem though this does seem quite obscure. Any suggestions would be greatly appreciated
dd: error writing „/dev/mmcblk0“: I/O error “I/O error” (short for “input/output error”) means that there was a problem accessing a hardware. When you get this on a storage medium, it means that your storage medium is dead or dying, or you have a loose wire or underpowered peripheral or some other hardware problem. I/O error from an SD card means that it's dead. That's why no software lets you format it. The card isn't able to store data any more. Some of its area might still be usable, but it's missing some of the bits. Given the quality of card readers, it's possible that your card reader is broken and the card would work on another reader. But that's a rarer scenario, don't count on it. You can't fix an SD card. Throw the SD card away and use a working one.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236256", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138571/" ] }
236,328
Is there a way to check if a date argument is in the correct format (YYYY-MM-DD)? I got this from the web but it doesn't work for me: date "+%Y-%m-%d" -d "2015-10-11" > /dev/null 2>&1echo $? I am expecting a 0 result but that's not the case. Can someone tell some another way?
This will check for the correct format (YYYY-MM-DD) in bash (with built-in regex match): if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] then echo "Date $1 is in valid format (YYYY-MM-DD)" else echo "Date $1 is in an invalid format (not YYYY-MM-DD)"fi Run: ./script.sh 2015-12-10 Output: Date 2015-12-10 is in valid format (YYYY-MM-DD) It doesn't check if the date itself is valid, only the format (as stated in the question, "Check if a date argument is in the correct format (YYYY-MM-DD")) If you need to check the date format and validate the date value, try something like: if [[ $1 =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]] && date -d "$1" >/dev/null then echo "Date $1 is valid and matches the format (YYYY-MM-DD)"fi This will discard invalid dates like 0000-88-77 that pass the regex matching. (Credit goes to @glenn jackman for this suggestion.)
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236328", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138634/" ] }
236,365
In bash scripts I try to keep my variables local to functions wherever I can and then pass what I need out of functions like bellow #!/bin/bashfunction FUNCTION() { local LOCAL="value" echo "$LOCAL" # return this variable}GLOBAL=$(FUNCTION)echo "$GLOBAL" But is it possible to do this while including the function's own echos so that if the function has it's own messages to output I don't have to catch them in a variable #!/bin/bashfunction FUNCTION() { local LOCAL="value" echo "$LOCAL" # return this variable echo "This function is done now" # do not return this variable}GLOBAL=$(FUNCTION)echo "$GLOBAL" # should only echo 'value'
Anything that's printed by the function can be captured if you capture the right output stream. So the easiest way to print something and save some other output is to redirect the superfluous output to standard error: function FUNCTION() { local LOCAL="value" echo "$LOCAL" echo "This function is done now" >&2} Another possibility is to log to a file rather than printing log messages directly, for example using something like this: log() { printf '%s\n' "$@" > my.log} That said, Bash functions cannot return variables . The only actual "return" value is the exit code. For this reason ( and many others ), if you want reliable logging, return values, exception handling and more you'll want to use a different language like Python, Ruby or Java.
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/236365", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/89568/" ] }
236,382
The install guide for ack suggests installing the ack script using this command: curl http://beyondgrep.com/ack-2.14-single-file > ~/bin/ack && chmod 0755 !#:3 I assume that the !#:3 at the end is some kind of back-reference, but what does it mean? Is there an equivalent in zsh? Google has not been helpful.
This is a special syntax, expanded by bash. It also works for zsh. According to the bash man page (section HISTORY EXPANSION), the patternexpands as following: The event designator !# refers to the entire command line typed so far which is curl http://beyondgrep.com/ack-2.14-single-file > ~/bin/ack && chmod 0755 : splits between the event designator (this case the entire line)and the word designator (selects a sub-part) the word designator 3 which selects the third word/argument (counting of words starts at zero), in this case ~/bin/ack . The final command line (usually displayed before executed) is: curl http://beyondgrep.com/ack-2.14-single-file > ~/bin/ack && chmod 0755 ~/bin/ack . For details, see the bash manual or very similar the zsh manual
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/236382", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/2171/" ] }
236,391
I have a graphical machine of rhel7, when i run who command , one of the outputs in 2nd column is ':0'. What does ':0' mean ?
This is a special syntax, expanded by bash. It also works for zsh. According to the bash man page (section HISTORY EXPANSION), the patternexpands as following: The event designator !# refers to the entire command line typed so far which is curl http://beyondgrep.com/ack-2.14-single-file > ~/bin/ack && chmod 0755 : splits between the event designator (this case the entire line)and the word designator (selects a sub-part) the word designator 3 which selects the third word/argument (counting of words starts at zero), in this case ~/bin/ack . The final command line (usually displayed before executed) is: curl http://beyondgrep.com/ack-2.14-single-file > ~/bin/ack && chmod 0755 ~/bin/ack . For details, see the bash manual or very similar the zsh manual
{ "score": 6, "source": [ "https://unix.stackexchange.com/questions/236391", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138665/" ] }
236,424
I am trying to use command substitution in a bash script to output redirection symbols based on a variable like so: IS_VERBOSE=falsecurl $BLAH $( $IS_VERBOSE && echo '-i' || echo '> /dev/null' ) That is, if verbose, add the -i switch, otherwise, throw everything from stdout away. The problem is that when IS_VERBOSE is false, my command becomes curl $BLAH \> /dev/null More generally, command substitution escapes the characters > >> & | # $ and possibly others. How can I output these symbols without escaping using command substitution?
After the substition happens (which BTW in POSIX could only target the left side before any ">") there is no more evaluation on whether there is any ">" so the approach you envisioned wouldn't work. If you don't care about POSIX-conformity (after all you tagged this as 'bash') you could still find a solution by dynamically setting the right side but I would personally go for a totally different approach; have a look at the following post detailing a verbose/silent mode based on custom file descriptors: https://stackoverflow.com/a/20942015/2261442 . A code excerpt from that post to show how nice it would then look like: # Some confirmations:printf "%s\n" "This message is seen at verbosity level 3 and above." >&3printf "%s\n" "This message is seen at verbosity level 4 and above." >&4printf "%s\n" "This message is seen at verbosity level 5 and above." >&5
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236424", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/109962/" ] }
236,475
Is a "port" a communication endpoint (in the transport layer)? Is a "port number" an address assigned to a port? Given a port, can we change the port number assigned to it, similar tothat it is possible to change the IP address assigned to a network interface? From https://en.wikipedia.org/wiki/Network_socket sockets with TCP port 53 and UDP port 53 are distinct sockets What does the quote mean? Specifically, Can a port be used by two transport protocols (e.g. TCP and UDP) simultaneously? (My understanding is that a port is part of atransport protocol, and can't belong to another protocol even at adifferent time.) Does the quote mean that a port number 53 can be assigned to a port in TCP and to a port in UDP at different times (but notsimultaneously)?
A computer can have one or more IP addresses. Some IP protocols, like ICMP, only need IP addresses to communicate. Others, like UDP and TCP, require that packets be addressed to a port as well as an IP address. Generally you have a program implementing a service listen on a well-known port so that other systems know how to contact it. An ssh server will, for example, listen on port 22/tcp: $ netstat -a -tActive Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 *:ssh *:* LISTEN $ netstat -a -t -nActive Internet connections (servers and established)Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN The netstat program will give symbolic names to port numbers, by looking in /etc/services , and a program such as sshd would call getservbyname("ssh","tcp") to convert a name to a port number. If you listen on IP address 0.0.0.0 , that means to listen on all of a system's IP addresses, and that's why netstat prints a * . The ssh server doesn't have to listen on port 22. You can change its config file to listen on port 8022, say. As long as the remote user knows the port number, and any intervening firewalls allow traffic to port 8022, it'll work. For hundreds of services around the world, the well-known port numbers are maintained in the Service Name and Transport Protocol Port Number Registry . It's a superset of your local system's /etc/services . A socket is a communications endpoint. Before it can be used, it must be bound to an IP address, port number, and protocol. If it's using TCP, it must then be connected to another socket before packets can be exchanged. A server calls socket to create a socket, bind to bind it, and listen to listen for connections. A client uses socket and bind , then connect to connect to a server. (The call to bind is optional for a client; when connect is called, the system will allocate an unused port and pick an appropriate IP address to bind to the socket.) sockets with TCP port 53 and UDP port 53 are distinct sockets If a service can be offered on both TCP and UDP, it's customary for the port number to be the same in both protocols. In the above case, you'd probably have a single DNS server that creates two sockets, one listening on 0.0.0.0:53/tcp and the other listening on 0.0.0.0:53/udp . Some older services were designed to run on only one protocol, and in those cases you may see two services using the same port number (but of course on different protocols). For example, 512/tcp is for rexec, but 512/udp is for biff. Systems like this have completely different programs listening on the ports. rexecd listens on 512/tcp, and comsat listens on 512/udp.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236475", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/674/" ] }
236,487
Let's say I have this simple code: echo "Are there any arguments?"if [ $# -eq 0 ]; then echo "false"else echo "true"fi As you can see it would be better to just have opportunity to directly print condition result, but I don't know how to do it. It would be something like: echo "$([ $# -eq 0 ])" But it doesn't work that way. Can we do this without if ?
In this case you can use the list control operators && and || instead: [[ $# -eq 0 ]] && echo false || echo true[[ $# -eq 0 ]] && { echo false; } \ || { echo true; } The { } group a list of commands, you don't need them for just a single command, but they often make such constructions more readable (though a list also requires a terminating ; or newline). As noted by @Kusalananda, this works for simple code (like echo ) where commands return 0 ("true"): despite the lexical similarity the above does not have the same semantics as a short-circuited evaluation in C does, i.e.: (argc==1) && printf("false\n") || printf("true\n"); /* C, not bash */ A workaround where the command(s) might return a non-zero status is: [[ $# -eq 0 ]] && { echo false;:; } || { echo true; } where the extra " : " null command at the end of the first list ensures that it returns a 0 (true) status (the return status of a list is the exit status of the last command executed in the list). Though note the logic above is the inverse of an ordinary conditional logic test in order to match the question, the usual logic is [[ boolean-condition ]] && { true-actions;:; } || { false-actions; } or, to be clearer for this example: [[ $# -eq 0 ]] && { echo no arguments;:; } || { echo found arguments; } When you have two (or another defined number of states), you can also use an array with a computed index, as shown in Stéphane's answer: declare -a bool=([1]=true [0]=false)echo ${bool[ (($# == 0)) ]} or temperature=70declare -a porridge=([1]="too hot" [2]="just right" [3]="too cold")echo ${porridge[ (( temperature >= 75 ? 1 : temperature <= 68 ? 3 : 2 )) ]} This uses arithmetic expressions within (( )) , where 0 is false, opposite to the usual shell convention.
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236487", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138739/" ] }
236,498
I'm using Ubuntu 15.10 and i want to know which display server is running. In first version of Ubuntu it is definitely X server , but recently i got updated my Ubuntu 15.10 and i came to know that some Mir Server packages are going to be installed so how will i know that either Mir is running or X Server?
(Trying to improve @shcherbak answer.) To get info about the running display server write in the console: ps -e | grep tty The out put might be, for example: 1475 tty2 00:00:00 gdm-x-session 1478 tty2 00:00:40 Xorg 1489 tty2 00:00:00 gnome-session-b One of the tty* results is the terminal where you have the GUI in your linux system (usually tty7 though I use tty2 in my example). Therefore, this should be the terminal where the display server (X11, Mir, or whatever) is running. For example, the results show 1478 tty2 00:00:40 Xorg , so this would be running Xorg (that is, X11). Shscherbak answer would just output the running processes that contain a capital X, "X". Among others, of course, Xorg, in case it is present. But if another display server is running, you miss the information. :)
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236498", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/-1/" ] }
236,542
'4800483343' is a directory, and 'file1' & 'file2' are two files in it. Why is the following happening? $ ls 4800483343file1 file2$ md5sum 4800483343/*36468e77d55ee160477dc9772a99be4b 4800483343/file129b098f7d374d080eb006140fb01bbfe 4800483343/file2$ mv 4800483343 4800[48]3343$ md5sum 4800[48]3343/*md5sum: 4800[48]3343/*: No such file or directory$ md5sum '4800[48]3343'/*36468e77d55ee160477dc9772a99be4b 4800[48]3343/file129b098f7d374d080eb006140fb01bbfe 4800[48]3343/file2 What other characters cause this?
Answer for original question Why are square brackets preventing shell expansion Square brackets do not prevent shell expansion but quotes do. I suspect that the commands that you actually ran were as follows This runs md5sum on the files in dir/ : $ md5sum d[i]r/*02fdd7309cef4d392383569bffabf24c dir/file1db69ce7c59b11f752c33d70813ab5df6 dir/file2 This moves dir to d[i]r with the quotes preventing the expansion of the square brackets: $ mv dir 'd[i]r' This looks for directory dir which no longer exists: $ md5sum d[i]r/*d[i]r/*: No such file or directory Because of the quotes, the following looks in the new directory named d[i]r : $ md5sum 'd[i]r'/*02fdd7309cef4d392383569bffabf24c d[i]r/file1db69ce7c59b11f752c33d70813ab5df6 d[i]r/file2 Answer for revised question In the revised question, the directory 4800483343 exists and the following command run: mv 4800483343 4800[48]3343 What happens when this command is run depends on whether the glob 4800[48]3343 matches any existing directory. If no directory matches that, then 4800[48]3343 expands to itself 4800[48]3343 and the directory 4800483343 is moved to the directory 4800[48]3343 . Consequently: The command md5sum 4800[48]3343/* will return the error "No such file or directory" because no directory exists which matches the glob 4800[48]3343 . The command md5sum '4800[48]3343'/* will correctly find the files because the quotes prevent expansion of the glob. Examples of globs Let's create two files: $ touch a1b a2b Now, observe these globs: $ echo a[123]ba1b a2b$ echo a?ba1b a2b$ echo *ba1b a2b
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236542", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/85900/" ] }
236,581
This is a basic question regarding bash but I could not find a solution. I have many subdirectories with identically named files and I want to compare all of them for identity. I can return list of this files with find . -name "protein.mol2" I know that file can be used as query in diff diff -q --from-file dir1/file dir2/file dir3/file; echo $? How do I pipe the output of find to diff ?
The --from-file option allows you to compare one file against many files (rather than something like tar --files-from which reads a list of files to operate on from a file). It has an analogous --to-file , which of the two you use would depend on relative "direction" of the change. Since you're using -q which only says if there is a difference, this hopefully should not matter to you here. I assume you have a reference file, and you wish to compare it to a set of identically named files, so either of these should work: diff -q --from-file dir1/protein.mol2 $(find . -name protein.mol2)find . -name protein.mol2 | xargs diff -q --from-file dir1/protein.mol2 In the first case diff will run only once, and its exit code will reflect whether or not any differences were found in the set. In the second case diff may run more than once. This second form can be used in case you have a large number of files (or very long file/directory names) and hit a command argument limit (usually 128kB on Linux systems).
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236581", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/138814/" ] }
236,606
Is there a method of creating a symbolic file that refers to the contents of a directory? So for example, calling: cat all_keys would give the same output as: cat keys/key1+keys/key2+etc... I've tried creating a symbolic link to the directory, tried various flags to try and get the Data and even trying to make a symbolic link that runs the command: cat keys/* Akin to the manner in which Logical Volume can span multiple physical partitions, I'd like to know if I can create a file that spans an arbitrary and flexible length of data. For context: I'm getting really frustrated with the flatfile system used for ssh authorised_keys. I know I could use a SED to remove the key data but that seems messy. I'm sure there's other uses outside of this scope too. Thanks in Advance. Edit: In the end I just went with SED in place to make the deletions and comments before the key block to identify it. It's a little more expensive CPU wise than I'd have liked, but avoids either repeating all the key data in a folder and a file or trying to make a fuse directory.
The --from-file option allows you to compare one file against many files (rather than something like tar --files-from which reads a list of files to operate on from a file). It has an analogous --to-file , which of the two you use would depend on relative "direction" of the change. Since you're using -q which only says if there is a difference, this hopefully should not matter to you here. I assume you have a reference file, and you wish to compare it to a set of identically named files, so either of these should work: diff -q --from-file dir1/protein.mol2 $(find . -name protein.mol2)find . -name protein.mol2 | xargs diff -q --from-file dir1/protein.mol2 In the first case diff will run only once, and its exit code will reflect whether or not any differences were found in the set. In the second case diff may run more than once. This second form can be used in case you have a large number of files (or very long file/directory names) and hit a command argument limit (usually 128kB on Linux systems).
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236606", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/135104/" ] }
236,611
I am using the i3 tiling window manager . How can I add a printer (e.g. things like searching the network to auto-discover printers to connect to or supply a printer's coordinates). Unfortunately "i3 printer" is not very google-able as an actual printer named i3 exists.
i3 is a window manager, not a desktop environment. If you want a desktop environment, you'll have to add one; many DEs do support changing their window manager. If you just want to add a printer, you don't need to use an i3 -specific tool to do so. You can just use whatever other desktop's tools; or you can bypass them all and go directly to cups. This is done by pointing your webbrowser to http://localhost:631/ and configuring things there. If cups asks you for a username and password, note that cups is usually configured to use PAM for authentication. You can either use root and your root password to log in, or add a user to the group which is configured with the SystemGroup statement in cups-files.conf (on Debian and derivatives, this is the lpadmin group).
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/236611", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/24044/" ] }
236,637
Consider: $ echo '<H1>heading</H1>' | grep '<H\(1\|3\|2\)>.*</H\1>'$ <H1>heading</H1> and $ echo '<H1>heading</H3>' | grep '<H[1-3]>.*</H\1>'$ grep: Invalid back reference first command works just fine. Doesn't [1-3] and \(1\|3\|2\) both mean 1 or 2 or 3 ? if not why? and what the difference between them? why back-reference works with only \(\) ?
() means «groupping» which means set a part of the string which can operate as 1 item, and for backrefference too. [] means symbols set So if you use parenthesis just for single symbols the meaning is same. But usually it used for multisymbol strings like (cat|dog)
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236637", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/52733/" ] }
236,659
The GNU Coreutils manual for mv says: -f --force Do not prompt the user before removing a destination file. However, this already seems to be the default behaviour for mv , so the -f option appears to be superfluous. E.g. in GNU Bash version 4.3.11: $ ls -ltotal 0$ touch 1 2; mv -f 1 2; ls2$ touch 1 2; mv 1 2; ls2 It seems unlikely the intention of the -f flag is to override alias mv="mv -i" , because there are several standard ways of overriding an alias (e.g. using \mv ) that would do this more concisely and in a way that is consistent across commands. The manual notes that, "If you specify more than one of the -i, -f, -n options, only the final one takes effect," but it still seems unlikely the intention of the -f flag is to override the -i flag in general, because equivalent behaviour can be achieved by simply using mv , which is much more concise and comprehensible than using mv -if . That being the case, what is the purpose of the -f flag? Why does it exist?
The usage of -f is more clearly described in the man page from 4BSD, which was where the -f and -i options were added: If file2 already exists, it is removed before file1 is moved. If file2 has a mode which forbids writing, mv prints the mode and reads the standard input to obtain a line; if the line begins with y, the move takes place; if not, mv exits. Options: -i stands for interactive mode. Whenever a move is to supercede an existing file, the user is prompted by the name of the file followed by a question mark. If he answers with a line starting with 'y', the move continues. Any other reply prevents the move from occurring. -f stands for force. This option overrides any mode restrictions or the -i switch. An even more precise definition of how mv operates is given in the POSIX standard , which adds that -f only overrides -i if it occurs later in the command line. So the default behavior is a bit different from -f . The default is to ask for confirmation only when the target isn't writable. (This behavior goes back at least as far as V4 , where mv didn't take any options.) If the -i option is given, mv will additionally ask for confirmation whenever the target exists. The -f option will inhibit asking in both of those cases (if it occurs after any -i ).
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/236659", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/-1/" ] }
236,688
I have looked for this elsewhere but not able to find something that matches my requirements. The template below is the one I need to use : dn: uid=$1,ou=home,dc=chan,dc=comobjectClass: organizationalPersonobjectClass: personobjectClass: inetOrgPersonobjectClass: topcn: $2sn: $3userid: $1userPassword: I need to script in such a way that populates the following fields $1,$2,$3,$4 with the input that I give it and then outputs to a new file thus allowing to run it using the blank template.
I suspect you are looking for something quite simple like a file my_script that contains: cat <<XXXdn: uid=$1,ou=home,dc=chan,dc=comobjectClass: organizationalPersonobjectClass: personobjectClass: inetOrgPersonobjectClass: topcn: $2sn: $3userid: $1userPassword:XXX To use the above, simply run: sh my_script fred 100 200 which will output to stdout (and can be redirected to a file).
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/236688", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/18538/" ] }
236,746
I use gpg-agent sometimes with no X display or over ssh, so my config file contains: pinentry-program /usr/bin/pinentry-curses This way, the gpg passphrase is requested in curses. That said, in some graphical scripts, I wish to use the GTK pinentry instead. How to call gpg and temporarily use a different pinentry?
You can use the PINENTRY_USER_DATA environment variable to give gpg information to pass to the pinentry command. You then need to set pinentry-program to a custom wrapper such as this that will run the curses or the GTK pinentry depending on that variable. Note that this only seems to work with GPG 2.x, contrary to what the documentation of GPG 1.x says. So with that script , you use gpg2 to use pinentry-curses and PINENTRY_USER_DATA="gtk" gpg2 to use pinentry-gtk-2 .
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236746", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/8446/" ] }
236,751
I have a file which is having following content: zdkaaab12cdndkekdn Input1: aaa and cdn Output 1: aaab12cdn Input 2: zdk and dke Output 2: zdkaaab12cdndke I could use below commands to achieve: grep -a aaa -A2 file # Output 1grep -a aaa -A4 file # Output 2 But in the file I don't know what is the exact occurrence (position) of end string pattern (file is having 20000 rows) How can I achieve this?
grep won't help you here. This is a job better accomplished with sed using range expressions: $ sed -n '/aaa/,/cdn/p' fileaaab12cdn$ sed -n '/zdk/,/dke/p' filezdkaaab12cdndke sed -n suppresses the automatic printing, so that lines are printed just if explicitly asked to. And this happens when the range /aaa/,/cdn/ happens. These range expressions are also available in awk , where you can say: awk '/zdk/,/dke/' file Of course, all these conditions can be expanded to a more strict regex like sed -n '/^aaa$/,/^cdn$/p' file to check that the lines consist on exactly aaa and cdn , nothing else.
{ "score": 7, "source": [ "https://unix.stackexchange.com/questions/236751", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/81640/" ] }
236,813
I an trying to run this statement in bash and keep on getting errors test [[ "$(read -p 'Install gtodo? ' R ; echo $R)" == "Y" ]] && (sudo apt-get install gtodo) || (echo "gtodo not installed") Please, what's the correct syntax?
I believe the problem is that you are using both test and [[ test "$(read -p 'Install gtodo? ' R ; echo $R)" = "Y" && (sudo apt-get install gtodo) || (echo "gtodo not installed")
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236813", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/107346/" ] }
236,865
In SSH local forwarding: -L [bind_address:]port:host:hostport Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the remote machine. Port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of “localhost” indicates that the listen‐ ing port be bound for local use only, while an empty address or ‘*’ indicates that the port should be available from all interfaces. In "an empty address or * indicates that the port should be available from all interfaces", what do "all interfaces" mean? Does it mean all the network interfaces on the local host when the local host can have multiple network interfaces, and the port port can be used with all the network interfaces on the local host? In "The bind_address of localhost indicates that the listening port be bound for local use only", does "for local use only" mean a particular network interface on the local host? Can bind_address refer to a network interface on a host other than the local host?
In general, an address binding is an association between a service (e.g., SSH) and an IP address. A host may have multiple IP addresses (e.g., 127.0.0.1, 192.168.1.2). Address binding allows you to run a service on some or all of these addresses. Suppose your host is configured with two network interfaces, one connected to a trusted network (e.g., 192.168.1.0/24), the other connected to an untrusted network (e.g., 192.168.2.0/24). Say you want your host to accept SSH connections from the trusted network only. In this case, you would bind the SSH service to the host's address on the trusted network only (e.g., 192.168.1.2). Using localhost as bind_address would allow only SSH clients running on the local machine to connect to the SSH service.
{ "score": 5, "source": [ "https://unix.stackexchange.com/questions/236865", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/674/" ] }
236,875
I often do operations like paste <(cut -d, -f1 file1.csv) <(cut -d, -f1 file2.csv) which is very tedious with more than a few files. Can I automate this process, e.g. with globbing? I can save the cut results with typeset -A cut_resultsfor f in file*.csv; do cut_results[$f]="$(cut -d, -f1 $f)"done but I'm not sure how to proceed from there.
You can automate this with globbing, specifically the e glob qualifier , plus eval , but it isn't pretty and the quoting is tricky: eval paste *.csv(e\''REPLY="<(cut -d, -f1 $REPLY)"'\') The part between \'…\' is some code to execute for every match of the glob. It is executed with the variable REPLY set to the match, and can modify it. I put the code in single quotes so that it isn't expanded when the glob is parsed. The code REPLY="<(cut -d, -f1 $REPLY)" generates the string <(cut -d, -f1 file1.csv) if the match is file1.csv . The double quotes are necessary so that the part after the equal sign isn't expanded when the e code is executed apart from substituting the value of REPLY . Since each globbed file is replaced by a string, It would be nicer to hide the complexity in a function. Minimally tested. function map { emulate -LR zsh local cmd pre cmd=() while [[ $# -ne 0 && $1 != "--" ]]; do cmd+=($1) shift done if ((!$#)); then echo >&2 "Usage: $0: COMMAND [ARGS...] -- PREPROCESSOR [ARGS...] -- FILES..." return 125 fi shift while [[ $# -ne 0 && $1 != "--" ]]; do pre+="${(q)1} " shift done if ((!$#)); then echo >&2 "Usage: $0: COMMAND [ARGS...] -- PREPROCESSOR [ARGS...] -- FILES..." return 125 fi shift eval "${(@q)cmd}" "<($pre${(@q)^@})"} Sample usage (the syntax is reminiscent of zargs ): map paste -- cut -d, -f1 -- *.csv
{ "score": 4, "source": [ "https://unix.stackexchange.com/questions/236875", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/73256/" ] }