output
stringlengths
9
26.3k
input
stringlengths
26
29.8k
instruction
stringlengths
14
159
Looking at the Linux kernel docs it looks like it it's waiting for the lock to get freed. - HOWLockdep already has hooks in the lock functions and maps lock instances to lock classes. We build on that (see Documentation/locking/lockdep-design.txt). The graph below shows the relation between the lock functions and the various hooks therein. __acquire | lock _____ | \ | __contended | | | <wait> | _______/ |/ | __acquired | . <hold> . | __release | unlocklock, unlock - the regular lock functions __* - the hooks <> - statesSource: https://www.kernel.org/doc/Documentation/locking/lockstat.txtNOTE: Take a look at that link, it shows usage as well. Measuring contention By the way, you can/could use mutrace to calculate contention for a given executable as well. It's discussed here in this article titled: Measuring Lock Contention. For example $ LD_PRELOAD=/home/lennart/projects/mutrace/libmutrace.so gedit mutrace: 0.1 sucessfully initialized.mutrace: 10 most contended mutexes: Mutex # Locked Changed Cont. tot.Time[ms] avg.Time[ms] max.Time[ms] Type 35 368268 407 275 120,822 0,000 0,894 normal 5 234645 100 21 86,855 0,000 0,494 normal 26 177324 47 4 98,610 0,001 0,150 normal 19 55758 53 2 23,931 0,000 0,092 normal 53 106 73 1 0,769 0,007 0,160 normal 25 15156 70 1 6,633 0,000 0,019 normal 4 973 10 1 4,376 0,004 0,174 normal 75 68 62 0 0,038 0,001 0,004 normal 9 1663 52 0 1,068 0,001 0,412 normal 3 136553 41 0 61,408 0,000 0,281 normal ... ... ... ... ... ... ... ...mutrace: Total runtime 9678,142 ms.Referenceshttps://stackoverflow.com/questions/1963960/how-to-measure-lock-contention
I have been asked to measure the contention of locks a write process is causing. I was looking at the data of the lockstat for that write process. My questions are below:Is contention related to the number of times threads wait for the particular lock, as it is taken by another thread or the time for which threads have to wait for that lock to get freed? Is it correct to calculate the contention as a measure of both:nsec (avg amount of time threads have to wait for the event to occur/lock to get freed) and cnt (number of times event occurred) from profiling data collected from lockstat for a particular lock? i.e contention ~ nsec * cnt
What is contention? [closed]
I often hear that linux threads are heavy (requiring 8mb stack size)Can see where that claim comes from: A system (posix) thread's size depends on how you configure the task allocator. The default on modern 64 bit systems is indeed 8 MB, because that size kind of makes sense. Usually it grows far less, and I'm not even sure you'd have to actually allocate that memory unless you actually hit all these pages – just as with any other piece of virtual memory address space: If you don't use it, there's no physical memory backing. Also, this is totally configurable, so if a program uses more, that's up to the programmer, not a systematic issue.their own green threads in userspace (allocating to the heap).I hear a lot of grandiose things about Go that turn out to be questionable (or wrong); this is among these. Doing your own stack management is of course possible – after all, libpthread doesn't do any magic – but the same stack amount will use the same amount memory. "allocating a stack on the heap" is an oxymoron; again, these are just regular virtual memory spaces, and the kernel positively doesn't care what you do in your own process' memory space. If anything about what Go does differently than software that uses pthreads (and not all multi-threaded software does!) is "greener", then they might be reusing stack pages of short-lived threads; and libpthread to the best of my knowledge does the same. Again, after all, nothing here is magic.This then allows handling say 100k connections instead of 10k connections."instead of 10k": [[quotation needed]]. I can write a bad server in an established language and then write a somewhat better server in my language of choice and come to the conclusion that my "favourite one" is faster, too. I'll note that modern network servers are still by and large not written in Go, and if you really go all the way down to dataplane application servers, where you not only do the thread handling in your own process but also the network buffer management, Go has largely proven to be unpopular. I'll give Go that the channel and short-lived workers are a nice concept, that languages like Erlang do properly.that this is why Rust moved away from them and went with async/await.err, Rust's std::thread's usage patterns proves this to be a false statement.But if green threads are so popular, why can't Linux provide its own extremely light weight threads?Because it does; Go uses Linux threads, so they can't be any heavier themselves than what Go does. How else would Go be able to have multiple threads than if the operating system continued executing the code that was running when it yielded? Any real go thread is a Linux thread; anything that is concurrent but doesn't get its own thread runs in a separate Linux thread, which comes from something that constitutes a thread pool or similar. This is by no means a Go feature or invention – thread pools and concurrency, futures and closures have been around roughly forever.
I often hear that linux threads are heavy (requiring 8mb stack size) and this is why languages like golang implement their own green threads in userspace (allocating to the heap). This then allows handling say 100k connections instead of 10k connections. As I understand it, one problem with this is interop with C, and that this is why Rust moved away from them and went with async/await. But if green threads are so popular, why can't Linux provide its own extremely light weight threads? In other words, why does every language needs to have its own complex thread scheduler ontop of the OS scheduler, when the OS seems better placed to make these scheduling decisions?
Why can't Linux provide lighter/green threads?
Multi-tasking systems handle multiple processes and threads regardless of the number of processors or cores installed in the system, and the number of "threads" they handle. Multi-tasking works using time-slicing: the kernel and every running process or thread each get to spend some time running, and then the system switches to the next runnable thread. The switches happen very frequently, which gives the impression everything is running in parallel even when it's not. All this happens without any change to the APIs etc. Multi-core systems need to be able to run more threads than they physically support anyway, the single-core case is just an instance of that. Describing a CPU as single-threaded refers to simultaneous multithreading (SMT, or hyper-threading in the Intel world), not the CPU's ability to run multiple threads (or processes, or tasks). Adding SMT features to a CPU doesn't add any instructions to help running threads, it just allows better use of the hardware in some circumstances.
The motivation behind this question arises from exploring the Intel Galileo gen2 board which has a single threaded processor.I'm looking for a conceptual explanation on what does that mean for all the userspace applications that rely on the existence of threading? Does this mean that the kernel needs to be patched so that the system calls for the threading invocation are emulated in software instead of relying on the CPU threading support?
Multithreaded applications on a single threaded CPU?
This is an area where terms tend to be overloaded β€” the same term is used with different meanings depending on the context. It’s not helped by the fact that the meaning commonly associated with various terms changes over time, so the age of the texts you’re reading is important. There are a number of aspects to distinguish, or at least, two main ones.User v. kernel threads can refer either to the execution context, or the management context. β€œKernel threads” in Linux usually refers to the former: a kernel thread is a thread run in the kernel, for the kernel’s purposes (in ps, you’ll see them as processes with names in square brackets, e.g. [kthreadd], [khugepaged]...). As mentioned in the SO answer, software v. hardware threads refers to the nature of the threads being discussed. In both cases, the concept of a thread is the idea of running multiple threads of execution in parallel. In the software sense, it’s a light-weight process; in the hardware sense, it’s a β€œlight-weight” CPU (in Intel parlance, a hyperthread).The β€œuser threads” you’re referring to are typically known as green threads. They are software threads managed in userspace, with no kernel involvement. As with many concepts which are implemented in the kernel and in userspace, their use evolves over time as the perception of costs moves: in the past, and on other operating systems, threads weren’t well supported by the kernel, so they were implemented in user space; then kernels improved, and software started using kernel threads; then new environments considered kernel threads to be too expensive, and so it goes. To answer your question, since user threads are software threads, the term β€œsoftware threads” includes them.
From this answer - software threads vs hardware threads, software threads are threads managed by OS. But I also learn another term called user threads, which are threads that's not kernel threads, i.e. the OS won't know about these threads. So does software threads include user threads? I didn't get any answer from stackoverflow, but I think the idea is the same in the context of Linux, I'm asking about the term used in Linux, thanks.For reference, I found an useful resource on Quora.
Does software threads include user threads?
From the user's guide, section 4, "O2CB Cluster Service":NM: Node Manager that keep[sic] track of all the nodes in the cluster.conf
I am studying OCFS2 kernel source code and I found this comment of function dlm_lanuch_thread in file fs/ocfs2/dlm/dlmthread.c:/* Launch the NM thread for the mounted volume */So what does the "NM thread" mean?
What's a NM thread?
From man 1 traceroute: -m max_ttl Specifies the maximum number of hops (max time-to-live value) traceroute will probe. The default is 30.
Some of the servers I use traceroute on, are more than 30 hops away. How do I make traceroute trace beyond 30 hops?
How to make traceroute trace beyond 30 hops?
What traceroute does is use the option fields as it sends internet control message protocol (icmp) packets. Each Gateway or routing point in the network reads packets on one interface, decides where they ought to go, and writes them out on another interface. That interface is presumably closer to the destination. While the router is forwarding the packet it also makes modifications to the packet header. It reduces the "time to live" or hop count field by one. Each Gateway in the path of the packet toward the destination decreases this field. When the hop count field drops to zero, many routers will send back an icmp message saying where the packet was dropped. In order to find which IP address is a specific distance away, traceroute will send packets with the options of time to live & give me a response when it times out. messages with hop counts starting at 1 and ramping way up will each return the IP address of progressively more distant routers. Because traceroute does this multiple times you're going to get back (if you have a richly connected network, as is the internet) multiple answers at some of the counts. it may be the case that a particular Gateway will answer at different amounts away because the route to that gateway went through different hops.
Here is the route path from my home to sina.com.cn. traceroute -n sina.com.cn traceroute to sina.com.cn (202.108.33.60), 30 hops max, 60 byte packets 1 192.168.31.1 0.476 ms 0.587 ms 0.695 ms 2 140.0.5.1 2.557 ms 2.699 ms 3.065 ms 3 221.11.155.65 4.501 ms * 221.11.165.9 5.045 ms 4 * 221.11.156.18 26.480 ms 221.11.165.233 22.950 ms 5 219.158.9.97 14.176 ms * 219.158.19.149 21.472 ms 6 219.158.9.97 18.142 ms 219.158.8.81 44.856 ms 52.539 ms 7 124.65.194.190 53.162 ms 219.158.8.81 50.614 ms 124.65.194.190 47.266 ms 8 124.65.194.190 50.760 ms 61.148.143.26 49.351 ms 53.515 ms 9 210.74.176.138 43.056 ms 43.286 ms 61.148.143.26 53.712 ms 10 202.108.33.60 46.385 ms 210.74.176.138 42.896 ms 46.931 ms192.168.31.1 is my home router. 140.0.5.1 is my public ip the ISP provides. curl ifconfig.me 140.0.5.1 In the third line ,it says 3 221.11.155.65 4.501 ms * 221.11.165.9 5.045 msWhy there are two ip addresses 221.11.155.65 and 221.11.165 ? What does it mean? Does the packet jump from 140.0.5.1 to 221.11.155.65 ,then jumps from 221.11.155.65 to 221.11.165 ?
Why does traceroute display many ip addresses for the same hop?
Ok, as Stephen Kitt said there is no ready to use traceroute binaries for Cygwin. That's why i tried to compile it myself. I can see there is modern traceroute but from it's description follows, that it can't be used with old Linux kernels and for me compilation stuck on missing "dccp.h" and i gave up. I was able to compile the old implementation, but it works like it can not see ICMP replies on TTL exceeded (there are asterisks instead of results):1 * * * 2 * * *Maybe it requires some fixes to work on Cygwin and that's is the reason why there is no traceroute package for Cygwin. I checked with Wireshark and see it uses UDP test packets and corresponding ICMP replies are delivered correctly. I want to notice that this old traceroute works slowly like Win's tracert ("querying" nodes one by one). Modern traceroute gives results very quickly.
The implementation of traceroute(tracert) differs on Windows and Unix. I wanted to compare both with Wireshark. I am on Windows 7 now and I wanted to get Unix traceroute implementation quickly. My first idea was to get it using MSYS or Cygwin. I installed Cygwin with "inetutils*" packages checked, but there is no traceroute command and corresponding executable in /usr/bin/. I also tried searching for "traceroute" with Cygwin package search and found this substring in list of "zsh" files. I installed zsh and tried traceroute and tcptraceroute with no results. Which package should i check for installation of traceroute and is there traceroute for Cygwin at all?
How to get traceroute on cygwin?
A likely reason for the difference is that by default Window's tracert uses ICMP, whereas Linux traceroute defaults to UDP. Using the -I option for traceroute should produce the same results as tracert: traceroute -w 10 -I google.itFrom the traceroute documentation:In the modern network environment the traditional traceroute methods can not be always applicable, because of widespread use of firewalls. Such firewalls filter the "unlikely" UDP ports, or even ICMP echoes. To solve this, some additional tracerouting methods are implemented (including tcp), see LIST OF AVAILABLE METHODS below. Such methods try to use particular protocol and source/destination port, in order to bypass firewalls (to be seen by firewalls just as a start of allowed type of a network session). LIST OF AVAILABLE METHODS In general, a particular traceroute method may have to be chosen by -M name, but most of the methods have their simple cmdline switches (you can see them after the method name, if present). default The traditional, ancient method of tracerouting. Used by default. Probe packets are udp datagrams with so-called "unlikely" destination ports. The "unlikely" port of the first probe is 33434, then for each next probe it is incremented by one. Since the ports are expected to be unused, the destination host normally returns "icmp unreach port" as a final response. (Nobody knows what happens when some application listens for such ports, though).
I'm a Linux Mint user. I've run traceroute on Linux and tracert on Windows. On Linux, I just get asterisks. Everything seems to work fine on Windows. Here are the outputs Windows:Linux Mint:Why is this happening and is there something I can do to solve this problem?
Traceroute doesn't work on Linux, on Windows it does
From your output, you are not able to reach the destination. The * denotes a timeout. traceroute command shows the path to your destination. packets send to will pass through the routers and you receive a response obeying the time to live (TTL) value for each packets. the * denotes a timeout as a response from the intermediate routers that says the packet has expired. This could be due to various reasons. Either the TTL value is not enough, or could be that a firewall or router is denying the trace packets. In which case you cannot always confirm that the destination server is in fact down. Search google on traceroute command, you will get plenty of resources.
how to determine if the server is slow or not with traceroute unix command . Here is the traceroute Out put of a host IP . traceroute 188.165.247.43 traceroute to 188.165.247.43 (188.165.247.43), 30 hops max, 60 byte packets 1 iPhone.local (172.20.10.1) 1.493 ms 2.546 ms 3.287 ms 2 * * * 3 10.52.141.50 (10.52.141.50) 782.228 ms 784.069 ms 786.188 ms 4 10.52.141.54 (10.52.141.54) 786.491 ms 786.510 ms 786.927 ms 5 10.52.92.237 (10.52.92.237) 787.157 ms 788.059 ms 788.001 ms 6 aircel-gprs-177.5.251.27.aircel.co.in (27.251.5.177) 787.140 ms 98.452 ms 100.978 ms 7 114.79.219.41 (114.79.219.41) 158.391 ms 161.252 ms 161.610 ms 8 abs-cn-61.194.148.202.aircel.co.in (202.148.194.61) 178.216 ms 175.575 ms 193.356 ms 9 114.79.196.185 (114.79.196.185) 197.859 ms 218.156 ms 220.694 ms 10 abs-cn-129.198.148.202.aircel.co.in (202.148.198.129) 221.497 ms 238.732 ms 157.212 ms 11 * * * 12 * * * 13 125.17.180.149 (125.17.180.149) 137.955 ms 157.563 ms 139.677 ms 14 AES-Static-137.36.144.59.airtel.in (59.144.36.137) 289.250 ms 310.797 ms 290.745 ms 15 * * * 16 * * * 17 * * * 18 * * * 19 * * * 20 * * * 21 * * * 22 * * * 23 * * * 24 * * * 25 * * * 26 * * * 27 * * * 28 * * * 29 * * * 30 * * *is it possible to determine whether remote server is responding good or not by looking at the output ?
How to use traceroute command in unix
The traceroute manpage says !X indicates one of the ICMP error responses (other than the desired "TTL exceeded"). traceroute gives up when it sees one. It looks like mtr is more robust. It's a weird case. I can't think why you'd replace a "TTL exceeded" response with "administratively prohibited", when packets with a large enough TTL are simply let through. Thanks to mtr for tolerating this weirdness :).After the trip time, some additional annotation can be printed: !H, !N, or !P (host, network or protocol unreachable), !S (source route failed), !F (fragmentation needed), !X (communication administratively prohibited), !V (host precedence violation), !C (precedence cutoff in effect), or ! (ICMP unreachable code ). If almost all the probes result in some kind of unreachable, traceroute will give up and exit.
My traceroute6 results are truncated, while the results from mtr span the whole path. Why would this happen? mtr uses ICMP ECHO by default, just like traceroute. Running traceroute under sudo does not change the result. Nor does -M tcp or -M udp or -M icmp. (Note I am deliberately testing the "production version of IP". The legacy "experimental version" works as expected :-). mtr $ time mtr -n --report -c 1 google.co.uk Start: Thu Aug 11 11:29:08 2016 HOST: localhost.localdomain Loss% Snt Last Avg Best Wrst StDev 1.|-- fdaa:bbcc:ddee:0:924d:4af 0.0% 1 5.7 5.7 5.7 5.7 0.0 2.|-- ??? 100.0 1 0.0 0.0 0.0 0.0 0.0 3.|-- ??? 100.0 1 0.0 0.0 0.0 0.0 0.0 4.|-- ??? 100.0 1 0.0 0.0 0.0 0.0 0.0 5.|-- 2a00:2380:3013:9000::8 0.0% 1 23.1 23.1 23.1 23.1 0.0 6.|-- 2a00:2380:13::23 0.0% 1 23.2 23.2 23.2 23.2 0.0 7.|-- 2a00:2380:2001:5000::d 0.0% 1 19.2 19.2 19.2 19.2 0.0 8.|-- 2001:4860:0:1::1049 0.0% 1 13.0 13.0 13.0 13.0 0.0 9.|-- 2001:4860:0:1::8f 0.0% 1 19.6 19.6 19.6 19.6 0.0 10.|-- 2a00:1450:4009:809::2003 0.0% 1 24.0 24.0 24.0 24.0 0.0real 0m6.229s user 0m0.002s sys 0m0.011straceroute6 $ time traceroute -6 -n google.co.uk traceroute to google.co.uk (2a00:1450:4009:809::2003), 30 hops max, 80 byte packets 1 fdaa:bbcc:ddee:0:924d:4aff:fe06:1c9 3.351 ms 3.324 ms 5.569 ms 2 * * * 3 * * * 4 2a00:2302::1103:100:37 20.128 ms !X 20.118 ms !X 20.120 ms !Xreal 0m0.221s user 0m0.000s sys 0m0.006stracepath6tracepath is similar to traceroute, only does not require superuser privileges and has no fancy options. It uses UDP port port or some random port. tracepath6 is [a] good replacement for traceroute6 and [a] classic example of application of Linux error queues.$ time tracepath6 -n google.co.uk 1?: [LOCALHOST] 0.035ms pmtu 1488 1: fdaa:bbcc:ddee:0:924d:4aff:fe06:1c9 4.101ms 1: fdaa:bbcc:ddee:0:924d:4aff:fe06:1c9 3.161ms 2: no reply 3: 2a00:2302::1103:100:36 17.379ms asymm 5 4: 2a00:2302::1103:100:37 17.222ms !A Resume: pmtu 1488 real 0m5.068s user 0m0.001s sys 0m0.005sResults vary slightly between runs: sometimes hop 3 is not shown. The addresses of hop 3 or 4 also happen to change (regardless of the tool used); it looks like two different paths are used. When mtr is run interactively, it's eventually able to find hop 3 (though not hop 4). That hop shows 80-90% loss. (As noted on the NANOG list, expert networking knowledge is required to fully understand the output of tools like mtr :-).
Why is mtr more reliable than traceroute, on my ISP?
With traceroute you've to enter maximum hop as 1 using m1 option as follows. traceroute -m1 google.comAccording to basic rules of computer network Gateway and host must be connected to same NIC of router. Otherwise Data Link Layer will unable to deliver packets from hosts to Gateway. So it's hop should be 1. So by setting maximum hop as one and tracing any host will prit Gateway only.
I can't find any info regarding this in the man-pages. How would one go about only printing the gateway using traceroute?
traceroute, only print gateway information
Of course, you can use any protocol. Try tcptraceroute. Or the standard traceroute. from man page: -I, --icmp Use ICMP ECHO for probes -T, --tcp Use TCP SYN for probes -U, --udp Use UDP to particular destination port for tracerouting (instead of increasing the port per each probe). Default port is 53 (dns). -UL Use UDPLITE for tracerouting (default port is 53). -D, --dccp Use DCCP Requests for probes. -P protocol, --protocol=protocol Use raw packet of specified protocol for tracerouting. Default protocol is 253 (rfc3692).
I often run into a situation where I want to traceroute an IP without root or NET_RAW cap in Linux. I have attempted to send a UDP packet with a small TTL but no ttl error is emitted at all. It seems that getting the TTL exceeded error requires using an ICMP socket. Is it possible to use UDP or TCP protocol only without involving ICMP while still getting notified for TTL error so that I can traceroute with limited capabilities?
It is possible to traceroute without touching ICMP?
TL;DR By default, it starts at 33000 and goes up. You can observe it if you run a network trace at the same time: tcpdump -i any -n host 8.8.8.8 & mtr -u --report -c 1 8.8.8.8 21:21:50.777482 IP [redacted].31507 > 8.8.8.8.33000: UDP, length 36 21:21:50.877579 IP [redacted].31507 > 8.8.8.8.33001: UDP, length 36 21:21:50.977694 IP [redacted].31507 > 8.8.8.8.33002: UDP, length 36 21:21:51.077850 IP [redacted].31507 > 8.8.8.8.33003: UDP, length 36 21:21:51.177966 IP [redacted].31507 > 8.8.8.8.33004: UDP, length 36 21:21:51.278081 IP [redacted].31507 > 8.8.8.8.33005: UDP, length 36 21:21:51.378198 IP [redacted].31507 > 8.8.8.8.33006: UDP, length 36 21:21:51.478341 IP [redacted].31507 > 8.8.8.8.33007: UDP, length 36 21:21:51.578498 IP [redacted].31507 > 8.8.8.8.33008: UDP, length 36 21:21:51.678646 IP [redacted].31507 > 8.8.8.8.33009: UDP, length 36 21:21:51.778801 IP [redacted].31507 > 8.8.8.8.33010: UDP, length 36 21:21:51.878949 IP [redacted].31507 > 8.8.8.8.33011: UDP, length 36 21:21:51.979117 IP [redacted].31507 > 8.8.8.8.33012: UDP, length 36Here is why in the code. The source code is at https://github.com/traviscross/mtr If you analyze it, you observe the different behavior between TCP and UDP during parsing of command line arguments: case 'u': if (ctl->mtrtype != IPPROTO_ICMP) { error(EXIT_FAILURE, 0, "-u , -T and -S are mutually exclusive"); } ctl->mtrtype = IPPROTO_UDP; break; case 'T': if (ctl->mtrtype != IPPROTO_ICMP) { error(EXIT_FAILURE, 0, "-u , -T and -S are mutually exclusive"); } if (!ctl->remoteport) { ctl->remoteport = 80; } ctl->mtrtype = IPPROTO_TCP;So no port is set by default for UDP, where it is 80 by default for TCP. mtr.h has #define MinPort 1024 #define MaxPort 65535but this is misleading, the true stuff happens in ui/net.c.net_send_query calls new_sequence and the results is passed among other things to send_probe_command new_sequence in this file has static int next_sequence = MinSequence;Now, after a lot of hops you arrive in set_udp_ports which has: if (param->dest_port) { ... } else { udp->dstport = htons(sequence);In short, the "sequence" number is really the UDP destination port. And if we go back at ui/net.c we see it is defined as: #define MinSequence 33000 #define MaxSequence 65536
traceroute sends UDP packets to port 33434 (and up) by default. I assume mtr -u (manual, homepage, github) does the same, but I can't find any documentation or test results to verify the destination port numbers. Does mtr -u use destination port 33434 and then increment, like traceroute?
What UDP destination port(s) does mtr -u use?
You need to type traceroute -s with addresses which directly assign to any interfaces on your server. You can type any of this addresses from your output of ip a: 192.168.111.xyz 192.168.111.xyzzBut not real public ip because it has assigned to your other device (e.g. router). See man traceroute:-s source_addr, --source=source_addr Chooses an alternative source address. Note that you must select the address of one of the interfaces. By default, the address of the outgoing interface is used.
I have the below error: [root@~]# traceroute -s 'publicIP' 8.8.8.8 traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 60 byte packets **bind: Cannot assign requested address**But when i did not enter source, it works fine: [root@pf-apispens ~]# traceroute 8.8.8.8 traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 60 byte packets 1 192.168.111.1 (192.168.111.1) 1.759 ms 1.728 ms 1.649 ms 2 * * * 3 172.24.7.x (172.24.7.x) 1.752 ms 1.744 ms 1.816 ms 4 61.8.x.x (61.8.x.x) 1.635 ms 1.653 ms 1.632 ms[root@~]# ip addr {1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1454 qdisc pfifo_fast state UP qlen 1000 link/ether fa:16:3e:a7:5c:d0 brd ff:ff:ff:ff:ff:ff inet 192.168.111.xyz/24 brd 192.168.111.255 scope global eth0 inet 192.168.111.xyzz/32 scope global eth0 inet6 fe80::f816:3eff:fea7:5cd0/64 scope link valid_lft forever preferred_lft forever 3: eth1: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN qlen 1000 link/ether fa:16:3e:1d:e7:7a brd ff:ff:ff:ff:ff:ff[root@~]# route -n Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 192.168.111.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 172.27.0.0 192.168.111.2 255.255.254.0 UG 0 0 0 eth0 0.0.0.0 192.168.111.1 0.0.0.0 UG 0 0 0 eth0Please advice me on resolution. Do let me know if you need more information. Thanks in advance :)
traceroute have error bind: Cannot assign requested address
First, they're called "packets", not "packages". Multiple packets result in more information. Soft failure, asymmetric routing, and other network weirdness can't be seen with a single packet. With 2 packets, which result do you believe? With 3 packets, ... OTOH, programmer picked a default.
I'd like to learn why traceroute sends three packets per hop by default. (Nothing important, I'm just curious). Edit: packages != packets
Why does traceroute send three packets?
Analysis From what I can gather looking over the docs & via Google it looks like mtr is tracking packet loss itself by sending traffic and then keeping track of any drops that occur due to network congestion. For example, the Linode tutorial titled: Diagnosing Network Issues with MTR states the following:The i option flag runs the report at a faster rate to reveal packet loss that can occur only during network congestion. This flag instructs MTR to send one packet every n seconds. The default is 1 second, so setting it to a few tenths of a second (0.1, 0.2, etc.) is generally helpful.The nature of this traffic is ICMP ECHO requests. -i SECONDS --interval SECONDS Use this option to specify the positive number of seconds between ICMP ECHO requests. The default value for this parameter is one second.And that method of measuring loss is why you can have loss. mtr is not using TCP to measure any loss, it's using ICMP, which can and does have packets that either get dropped or timeout. What about Snt? The column Snt is telling you how many ICMP ECHO packets have been "sent".
I thought TCP protocol itself will guarantee not to loose any bytes while connecting. About this viewpoint, please refer to https://stackoverflow.com/questions/23841896/will-tcp-connection-lose-packets What puzzled me was how mtr (run with TCP protocol) calculate loss? TCP just has segment rather than packets. So, what 'Snt' means? [root@ ~]# mtr --report --tcp --port=443 stackoverflow.comhere, if some of intermediary hosts do not want to reply at all hence Loss% = 100.0, some of them reply ACK hence Loss% = 0.0, then how to explain hops #14 loss% = 25.0%?
How does MTR (run with TCP protocol) calculate the loss rate?
First, since your browser makes connections to multiple hosts, you need to know which one to check (if you don't already). There are a number of tools that can passively gather TCP statistics. Now, mtr is a tool specifically created to measure connection reliability and output reports that can be sent to ISPs verbatim. It makes traceroute and ping effectively obsolete for that task. Normally (without -r), it runs constantly, accumulates and updates stats of latency and loss percentage at each hop. Diagnosing Network Issues with MTR article includes some common patterns that you can see in results and how to interpret them. Since at least 0.75, mtr can use TCP SYN rather than ICMP packets with -T -P <port>, so you'll get stats for the same TCP ports as your normal traffic.
I'm using the traceroute utility to test network connectivity. The problem is usually with slow speed - that means, the webpages in the browser are often displayed very slowly. Sometimes the speed of rendering HTML page is better, but the videos from youtube are transfered very slowly, so that you can watch it usually with many pauses. I'd like to identify from the output of traceroute utility or it's combination with other utilities (such as ping, mtr and other) where the problem on the trace is. It means to use the combination of the utilities repeatedly to output some logs or statistics from which a decision can be made if the problem with slow response (or often connetivity loss) is caused by my closer ISP (three wireless routers) or his ISP. I would like to have some data I can provide them in case of connectivity or speed issues (it's really unreliable connection, very often problems).
Traceroute - approach the place with connectivity issues
You did not use fully-qualified domain names. www.google.com is not a fully-qualified (human readable form) domain name. It does not end with a dot. You also have a search path of plannersys.net. configured in your DNS client library and a wildcard DNS resource record for *.plannersys.net.. As a consequence of these, wget and tranceroute looked up the fully qualified domain name www.google.com.plannersys.net. and received the IP address 75.102.21.14 as the result. Your DNS client library, remember, turns non-fully-qualified domain names into fully-qualified domain names using the configured search paths and then issues lookups for the fully-qualified names. nslookup differed because it uses a different, internal, DNS client library. Amusingly, this is one instance where it did not differ from ping, but that is probably because your DNS client library is configured with multiple proxy DNS servers that do not all present the same view of the DNS namespace, or you have something like systemd-resolved in the mix that is changing your DNS client configuration on the fly. There is zero information about your DNS client library in your question, so there is not enough information from you for anyone to determine exactly why this is. Further readingJonathan de Boyne Pollard (2017). What DNS name qualification is. Frequently Given Answers. Jonathan de Boyne Pollard (2003). Why the results from nslookup are different to the operation of ping. Frequently Given Answers. Jonathan de Boyne Pollard (2004). DNS diagnosis tools. Frequently Given Answers.
We have a managed server with centos, recently it starts showing strange behavior: root@server [/tmp]# ping www.google.com PING www.google.com (172.217.8.196) 56(84) bytes of data. 64 bytes from ord37s09-in-f4.1e100.net (172.217.8.196): icmp_seq=1 ttl=53 time=24.8 msSo this looks quite good. And here it becomes strange. We get our own server instead of the google server! root@server [/tmp]# traceroute www.google.com traceroute to www.google.com (75.102.21.14), 30 hops max, 60 byte packets 1 server.plannersys.net (75.102.21.14) 0.041 ms 0.017 ms 0.015 msNslookup, however, looks good: root@server [/tmp]# nslookup > www.google.com Server: 8.8.8.8 Address: 8.8.8.8#53Non-authoritative answer: Name: www.google.com Address: 172.217.8.196 > ^CAnd wget and lynx also give us our own server. root@server [/tmp]# wget https://www.google.com --2017-12-04 11:50:56-- https://www.google.com/ Resolving www.google.com... 75.102.21.14 Connecting to www.google.com|75.102.21.14|:443... connected. ERROR: no certificate subject alternative name matches requested host name β€œwww.google.com”. To connect to www.google.com insecurely, use β€˜--no-check-certificate’.And with lynx: SSL error:host(www.google.com)!=cert(troutaccess.com)-Continue? (y)What can be the reason for this? Why do traceroute and wget and lynx use different addresses?
Why does ping resolve to a different address than traceroute? and lynx?
In most of these cases, the problem comes from the IP being blocked on the server for security reasons such as too many failed login attempts and the such. That kind of situation can only be resolved by the host's security team or waiting long enough for the automatic block to be removed, typically 24 hours.
EDITED: SOLUTION FOUND: After contacting godaddy, a solution was found very fast (great service!). What seemed to be the problem was that my IP Address was being blocked, given that I had too many failed login attempts. After requesting the IP to be unblocked and waiting a little bit the problem was solved. If the godaddy representative that attended the call is reading this THANK YOU DUDE!I have a godaddy account (shared hosting), and it comes with the ability to use the linux terminal via SSH Access. When I first obtained PuTTy, everything was working fine, however I tried to login 10 (more or less) different times with the wrong Username and Password, and now every time I click Open in PuTTy, I get the black terminal page but with this popup error message: Network error: Software caused connection abortHere is the actual image: https://i.sstatic.net/i6icL.png I don't even have the option to type anything in the black terminal anymore and no writing appears inside the terminal, as if it were frozen. I contacted Godaddy (great service btw) and we did the following tests:Downloaded putty on my other laptop, got same error when attempting connection Godaddy managed to log in themselves via SSH and managed without a problem I constantly used the "enable" option in godaddys CPanel under SSH Access, so that was not the problemThe final test we did was I entered my cmd.exe and ran the following command: tracert 108.blah.blah.blah108.blah.blah.blah represents the IP Address of my websites, and there is where we found a problem. I was obtaining a lot of values like 147 ms, and I also had 5 lines that appeared like: * * * here is an img of the tracert results https://i.sstatic.net/W0lme.png Godaddy mentioned that this seemed to be the issue and to contact my ISP, though what I can't figure out is why when I first ran PuTTy, I had absolutely no problem with it until I failed to access the account 10 times (more or less). I told that to Godaddy, and that maybe there might be some config file not giving me access because it believes I might have tried to hack inside, though it appears they didn't find anything. QUESTION: does anyone know what might be the problem here? I personally don't see it being an ISP problem if I had access in the beginning, so might someone know if there is a firewall issue somewhere on godaddy's linux server? Also I tried entering at different times of the day for two days and had the same problem, so I don't believe personally it is a connection issue.
PuTTY (SSH) (tracert) Network error: Software caused connection abort
you could use fping output as nmap target list: fping -aqg ip/24 | xargs nmap -sn --tracerouteIf your problem is that some gateway in your network is giving fake ARP responses (generating false positives), you can use -sn -PE to fix that: nmap -sn -PE --traceroute ip/24That way, nmap will exclusively show a host (and make a traceroute) if the host reply the ICMP request (ping).
First I try running nmap -sn ip/24 to check live hosts on a subnet. It returns that all 255 hosts are live which I know is not true. I do fping -g ip/24 and get that 7 hosts are up which makes more sense. Now I'm trying to figure out network topology using nmap -sn --traceroute ip/24 and the entire range of 0-255 is included. How can I just use the hosts that were returned by the fping command? I figure there has to be some way to pipe that argument or something to the nmap traceroute command, but I have no idea how to do this.
how to use only certain addresses in subnet for traceroute?
It would seem that ilportaledellautomobilista.it does not have an A record, however the domain does exist and does have a nameserver (SOA shows that). Since that host only has a SOA record, thats what dig is returning. www.ilportaledellautomobilista.it does have an A record though. So give that a try instead, and you will see that A records have been configured for it. Also ilportaledellautomobilista.it is being redirected to www.ilportaledellautomobilista.it (try and type ilportaledellautomobilista.it on its own in a web browser and you will see what I mean) The A record indicates the host's (domain name) IP. The SOA record indicates what the name server is for that domain. (basically which DNS server its managed from). Since the domain name itself does not have an A record specified, you will not get an IP address returned (thats what the A record is for, to specify an IP).
I have a domain and when I use dig jeeja.bizit just gives me my server ip address. ;; ANSWER SECTION: jeeja.biz. 13914 IN A 209.15.212.171But when I use the same command on another site: dig ilportaledellautomobilista.itthe replay is: ;; AUTHORITY SECTION: ilportaledellautomobilista.it. 3600 IN SOA dns.it.net. root.dns.it.net. 2012071209 86400 7200 604800 86400What is that and why there is no IP address? Why ping, nslookup and traceroute are not working on that specific address?
dig domain replay SOA
Answer turned out to be the router had 2 virtual interfaces on one physical interface. Problem was solved by getting iptables to use only the virtual interface eth0:0 for the routing.
I'm just in the process of setting up my Linux (Debian-based) router with a PPPoE connection via an ADSL/PPPoA -> PPPoE bridge. The connection works perfectly on the router itself but a traceroute through the NAT for some reason takes a long time to get the result of the first hop (to the NAT). The majority of the time the result of the hop will just be * * * but sometimes the hop does show up and there's a long delay before it tries the second hop. Here's when it doesn't show the hop at all: CallumsMacBookAir:~ Callum$ traceroute google.co.uk traceroute: Warning: google.co.uk has multiple addresses; using 173.194.41.95 traceroute to google.co.uk (173.194.41.95), 64 hops max, 52 byte packets 1 * * * //LONG DELAY 2 lo0-central10.ptn-ag03.plus.net (195.166.128.192) 22.578 ms 19.925 ms 20.990 ms 3 link-a-central10.ptn-gw01.plus.net (212.159.2.136) 19.574 ms 19.786 ms 19.343 ms 4 xe-5-3-0.ptw-cr01.plus.net (212.159.0.108) 19.540 ms 18.947 ms 25.387 ms 5 72.14.222.97 (72.14.222.97) 19.911 ms 19.706 ms 19.512 ms 6 209.85.246.244 (209.85.246.244) 19.423 ms 19.455 ms 19.655 ms 7 72.14.238.51 (72.14.238.51) 20.234 ms 24.666 ms 20.076 ms 8 lhr08s01-in-f31.1e100.net (173.194.41.95) 19.168 ms 19.518 ms 19.659 msSometimes it does respond in the first hop but there's still an asterisk: CallumsMacBookAir:~ Callum$ traceroute google.co.uk traceroute: Warning: google.co.uk has multiple addresses; using 173.194.41.95 traceroute to google.co.uk (173.194.41.95), 64 hops max, 52 byte packets 1 192.168.0.253 (192.168.0.253) 0.770 ms * 0.800 ms //LONG DELAY IN HERE 2 lo0-central10.ptn-ag03.plus.net (195.166.128.192) 20.301 ms 22.958 ms 32.719 ms 3 link-a-central10.ptn-gw01.plus.net (212.159.2.136) 19.142 ms 19.417 ms 18.527 ms 4 xe-5-3-0.ptw-cr01.plus.net (212.159.0.108) 19.047 ms 18.781 ms 18.887 ms 5 72.14.222.97 (72.14.222.97) 19.181 ms 19.424 ms 29.965 ms 6 209.85.246.244 (209.85.246.244) 33.559 ms 19.756 ms 25.363 ms 7 72.14.238.51 (72.14.238.51) 32.010 ms 19.753 ms 19.042 ms 8 lhr08s01-in-f31.1e100.net (173.194.41.95) 19.618 ms 19.730 ms *Is there any way to make the iptables router respond to the traceroute properly? Thanks!
iptables - masqueraded NAT has delayed first hop in traceroute
You need to install the traceroute package which provide the modern traceroute command: sudo apt install traceroute sudo apt remove inetutils-tracerouteOr -without removing inetutils-traceroute- you can use sudo update-alternatives --config traceroute to switch between traceroute versions.
I am trying to get traceroute installed with: $ sudo apt-get install inetutils-traceroute $ traceroute --version traceroute (GNU inetutils) 1.9.4 Copyright (C) 2015 Free Software Foundation, Inc.to work over TCP on Ubuntu 19.10 but it gives: $ traceroute -T google.com traceroute: invalid option -- 'T' Try 'traceroute --help' or 'traceroute --usage' for more information.Strange since this post: Wget and curl can work normally, but ping fails says that should be a valid option. But I don't find -T that on my system/version of traceroute: $ traceroute --help Usage: traceroute [OPTION...] HOST Print the route packets trace to network host. -f, --first-hop=NUM set initial hop distance, i.e., time-to-live -g, --gateways=GATES list of gateways for loose source routing -I, --icmp use ICMP ECHO as probe -m, --max-hop=NUM set maximal hop count (default: 64) -M, --type=METHOD use METHOD (`icmp' or `udp') for traceroute operations, defaulting to `udp' -p, --port=PORT use destination PORT port (default: 33434) -q, --tries=NUM send NUM probe packets per hop (default: 3) --resolve-hostnames resolve hostnames -t, --tos=NUM set type of service (TOS) to NUM -w, --wait=NUM wait NUM seconds for response (default: 3) -?, --help give this help list --usage give a short usage message -V, --version print program versionWorks fine without -T $ traceroute google.com traceroute to google.com (216.58.213.206), 64 hops max 1 x.x.x.x 8.310ms 8.447ms 8.461ms ... 10 x.x.x.x 22.349ms 18.459ms 21.743ms Any suggestions??
traceroute: invalid option -- 'T' (Ubuntu 19.10)
For getting details of network transactions, you have got a implementation of a Netflow generator for FreeBSD or Linux: ng_netflowNAME ng_netflow - Cisco's NetFlow implementation DESCRIPTION The ng_netflow node implements Cisco's NetFlow export protocol on a router running FreeBSD. The ng_netflow node listens for incoming traffic and identifies unique flows in it. Flows are distinguished by endpoint IP addresses, TCP/UDP port numbers, ToS and input interface. Expired flows are exported out of the node in NetFlow version 5/9 UDP datagrams.As for NetFlow itself:NetFlow is a network protocol developed by Cisco for collecting IP traffic information and monitoring network traffic. By analyzing flow data, a picture of network traffic flow and volume can be built.also rfc 3954 - NetFlow Services Export Version 9 For storing the Netflow data you also need what is know as a server collector. It can be either a Linux or a FreeBSD box. It should not be installed on the actual router. One such known implementation is nfsenNfSen is a graphical web based front end for the nfdump netflow tools. NfSen allows you to: - Display your netflow data: Flows, Packets and Bytes using RRD (Round Robin Database). - Easily navigate through the netflow data. - Process the netflow data within the specified time span. - Create history as well as continuous profiles. - Set alerts, based on various conditions. - Write your own plugins to process netflow data on a regular interval.Be aware that, depending on your available bandwidth, generating NetFlows can be taxing on the CPU. A known strategy in some cases is doing a mirror of the switch port of the router, and using another machine for those operations. After a certain threshold of bandwidth it probably makes more sense going for a professional router if generating NetFlows is a requirement. As a final alert, having NAT, the NetFlows have to be captured in the inside/LAN interface, as otherwise you will lose the sense of whom is doing what. I use up around 100GB of data for 5-6 months of traffic, using NfSen collecting NetFlow data from Cisco equipment, your mileage may vary.
I have a freebsd box, which serves as a router from LAN to the outside world. It has several Internet providers, OpenVPN servers and clients, NAT and so on. I would like to have complete statistics on when, who, to whom, via which provider, via which protocol, and how many bytes have been sent. I agree that the minimal time scale will be an hour, i.e. no need for millisecond precision. I tried vnstat2, ntopng and some other programs, but they don't seemed to have what I need or it is not obvious. I don't understand, why this feature is not easily available. But I am not good in freebsd, so please, give me some clues.
How to gather full network usage statistics on a freebsd router?
Old post, but for reference, it wouldn't work for a few reasons:The priority should be 16 and not 1 The filter handle should be 800::800 and not 800:800 You must supply the parent qdisc that the filter is attached toThis should work: tc filter del dev peth1 parent 1: handle 800::800 prio 16 protocol ip u32
How can I remove a single filter? tc filter show dev peth1shows filter parent 1: protocol ip pref 16 u32 filter parent 1: protocol ip pref 16 u32 fh 800: ht divisor 1 filter parent 1: protocol ip pref 16 u32 fh 800::800 order 2048 key ht 800 bkt 0 flowid 1:2 match 5bd6aaf9/ffffffff at 12Why does that not work?: tc filter del dev peth1 pref 1 protocol ip handle 800:800 u32
remove tc filter (Traffic Shaping)
To get the rate of B/s, no need of anything but your shell: Simply read rx_bytes file at each second and compare the current value with the value one second before. rx1=$(cat /sys/class/net/wlp3s0/statistics/rx_bytes) while sleep 1; do rx2=$(cat /sys/class/net/wlp3s0/statistics/rx_bytes) printf 'Download rate: %s B/s\n' "$((rx2-rx1))" rx1=$rx2 doneOf course, substitute wlp3s0 by the interface you want to monitor.
Playing around with some low level functions to monitor my system stats. I would like to get the current network utilization the same way like I can get cpu temp cat /sys/class/thermal/thermal_zone0/tempor fan speed cat /sys/class/hwmon/hwmon6/fan1_inputLooking at /sys/class/net/my_network_adapter/I didn't find a way to see the actual bandwidth consumption, rx_bytes just gives the total amount of data downloaded.
Get current network utilization via /sys/class/net
You state that I have stopped ntpdThen what you have been observing is nearly surely illegal activity. UDP/123 being a IANA-assigned port, it cannot be used by any other legitimate application: the Official IANA port assignment page states:Assigned ports both System and User ports SHOULD NOT be used without or prior to IANA registration.(System ports are defined higher up in the same document as ports in the range 0-1023). Port TCP/123 is used by a well-known piece of malware, showing that in compromised systems where root credentials have been obtained System ports are routinely used to smuggle illicit traffic. There are many plausible reasons for using UDP instead of TCP, possibly the most important one of which is the use of an encrypted VPN (in which case wireshark will not help you in the least), and for using a System Port (it is easier to evade detection if you use an innocent port). More than wireshark, your friend is ss: ss -lnup | grep 123will give you the ID of the process listening on port UDP/123. Anything but ntp, or, worse still, nothing, will mean you have been broken into. But we'll cross that bridge when we get there. EDIT: A follow-up to your comment. These pieces of evidence suggest you have been hacked:a mysterious service running on UDP/123, leaving no trace (which suggests the presence of a rootkit); a mysterious port-forwarding appearing on your router; connections from consumer accounts (check them on whatismyipaddress.com or with whois command). BTW, none of the three IP addresses you provided is even remotely connected with an ntp server. Your safest bet is to re-install your operating system, then change the configuration (including password!!) of your router (possibly disabling password login altogether in favor of the use of cryptographic keys) to allow only https connections. If you do not wish to re-install the OS because you have sensitive data, then take any Linux distribution running from a USB stick (Ubuntu is just fine), boot you pc from it (not from your hard disk), install clamav, rkhunter and chkroot on the USB key, and set them to work on your hard disk. This avoids the ability of some malware to evade detection by anti-malware programs because the disk on which the malware resides is being used passively, i.e. the programs on it are not being run. Also, remember that password protection (fail2ban notwithstanding) is not sufficient protection nowadays, and that you should always use cryptographic keys instead. Also, changing the default port for ssh connections makes you invisible at least to script kiddies (although any determined opponent will never be fooled by such a stratagem). Also, you may wish to read this post, including the answers, to get some more tips. Good luck.
I have noticing that, lately, my Odroid's ethernet LED is constantly blinking, even when I'm expecting no traffic. I ran iptraf and, besides the attempts of SSH brute force guess attempts (that are then blocked by fail2ban) I didn't see any TCP traffic. However, I noticed a massive amount of UDP traffic on port 123 that I have no idea where is coming from.| UDP (46 bytes) from 188.130.254.14:443 to 192.168.1.68:123 on eth0 | UDP (46 bytes) from 188.130.254.14:443 to 192.168.1.68:123 on eth0 | UDP (46 bytes) from 121.40.223.68:20630 to 192.168.1.68:123 on eth0 | UDP (46 bytes) from 45.63.62.141:33296 to 192.168.1.68:123 on eth0I configured my router to forward incoming UDP traffic on port 123 to an unknown IP address and still see a stupid amount of UDP packets on iptraf. Does anyone have any idea of what might be going on? Thanks!
Ubuntu - UDP Traffic on port 123
OK, not knowing what the limit is or how good you are at scripting, here a suggestion. Install vnstat - on Ubuntu that will automatically launch the accompanying demon process, which will immediately start monitoring the network (only for traffic stats, not content snooping). You can look at it interactively, like so: vnstat Database updated: 2023-09-30 09:40:00 enp0s31f6 since 2023-09-30 rx: 7.85 GiB tx: 93.23 MiB total: 7.94 GiB monthly rx | tx | total | avg. rate ------------------------+-------------+-------------+--------------- 2023-09 7.85 GiB | 93.23 MiB | 7.94 GiB | 26.88 kbit/s ------------------------+-------------+-------------+--------------- estimated 8.02 GiB | 93.93 MiB | 8.11 GiB | daily rx | tx | total | avg. rate ------------------------+-------------+-------------+--------------- today 7.85 GiB | 93.23 MiB | 7.94 GiB | 1.96 Mbit/s ------------------------+-------------+-------------+--------------- estimated 19.48 GiB | 231.46 MiB | 19.71 GiB |You can also extract just the transferred data by using a command line switch & e.g. awk. In the example below we're looking at 111 MB transferred. vnstat --oneline b |awk -F';' '{print $10/1024/1024}' 111.726You could stick that into a shell-script that you run from cron e.g. every 5 minutes, and compare the transferred volume against your threshold, and have the script stop the service. Let's say you're allowed 5 G of outgoing traffic in a month. #!/bin/bash [ $(/usr/bin/vnstat --oneline b |/usr/bin/awk -F';' '{printf "%d", $10/1024/1024}') -gt 5000 ] && /usr/bin/systemctl stop servicePut that in root's crontab and you're away laughing.
I am looking at a virtual server tariff that has limited outgoing traffic for a month, with billing if the traffic is exceeded. I would like to track the outgoing traffic automatically somehow, so that I can automatically can stop the service if the limit is being approached. What tool can I use for this in Linux? Thanks!
Limit outgoing traffic per month
vnstat is a CLI option. vnstat can run as a daemon that can be queried from CLI. apt-get install -y vnstat # install the software vnstat -u -i eth0 # enable monitoring of eth0 by default service vnstat restart # this may not work on Mint, I don't have a system to test with, but it does work on CentOS vnstat -h # show per-hour breakdown of traffic for the past 24 hours
I'd like to find out how much network traffic my computer uses, i.e. whether a limit of 30GB of transfer wouldn't be too little. What's the best tool to measure it? Using Linux Mint 17
Measure the network traffic on a long-term basis
As per @A.B comments:The mark you set in mangle/INPUT has no effect on tc, because tc ingress happens waaaay before. Check: en.wikipedia.org/wiki/Netfilter#/media/ ...To save the mark for the connection, use -j CONNMARK --save-mark for cgroup's outbound packets, retrieve connmark in inbound packets with tc-connmark, and finally, redirect packets to ifb to apply policer.Mark cgroup connection packets (Bidirectional):$ sudo iptables -A OUTPUT -t mangle -m cgroup --path '/user.slice/.../app-firefox-...scope' \ -j MARK --set-mark 0x11 $ sudo iptables -A OUTPUT -t mangle -j CONNMARK --save-markCreate ifb interface$ modprobe ifb $ ip link set ifb0 up $ tc qdisc add dev ifb0 root htb #For policing, we don't care about the qdisc typeRetrieve connmark and Redirect $IFACE ingress to ifb0$ tc qdisc add dev $IFACE ingress handle ffff: $ tc filter add dev $IFACE parent ffff: protocol all prio 10 u32 match u32 0 0 flowid 1:1 \ action connmark \ action mirred egres s redirect dev ifb0Apply policer on the marked packets in ifb0 root qdisc$ tc filter add dev ifb0 parent 1: protocol ip prio 20 handle 0x11 fw \ action police rate 1000kbit burst 10k dropThis will limit Firefox's download rate to 1000kbit.
I am trying to limit the download (ingress) rate for a certain app within a cgroup. I was able to limit the upload (egress) rate successfully by marking app's OUTPUT packets in iptables and then set a tc filter to handle that marked packets. However, when I did the same steps for ingress it didn't work.steps I followed to limit upload:Mark OUTPUT packets by their cgroup$ sudo iptables -I OUTPUT -t mangle -m cgroup --path '/user.slice/.../app-firefox-...scope'\ -j MARK --set-mark 11filter by fw mark (11) on the root qdisc$ tc qdisc add dev $IFACE root handle 1: htb default 1 $ tc filter add dev $IFACE parent 1: protocol ip prio 1 handle 11 fw \ action police rate 1000kbit burst 10k drop This limited the upload rate for firefox to 1000kbit successfully.steps I followed trying to limit download:Mark INPUT packets by their cgroup$ sudo iptables -I INPUT -t mangle -m cgroup --path '/user.slice/.../app-firefox-...scope'\ -j MARK --set-mark 22filter by fw mark (22) on the ingress qdisc$ tc qdisc add dev $IFACE ingress handle ffff: $ tc filter add dev $IFACE parent ffff: protocol ip prio 1 handle 22 fw \ action police rate 1000kbit burst 10k drop I am able to block app's download successfully with iptables: $ sudo iptables -I INPUT -t mangle -m cgroup --path '/user.slice/.../app-firefox-....scope' -j DROPSo it seems like iptables is marking cgroup's input packets but for some reason, tc can't filter them or maybe the packets are being consumed before tc filter takes effect? if so, then what is the use of marking input packets? If there is a way to block cgroup's input packets then there must be a way to limit them, right?
How to police ingress (input) packets belonging to a cgroup with iptables and tc?
User authorization events are typically logged by the system logging daemon in /var/log. The default locations vary between distros, but it is often /var/log/auth, /var/log/auth.log, /var/log/secure. I don't have a Gentoo system handy, but the default install used to feature syslog-ng and log these events to /var/log/auth.log. There are a variety of ways to audit network traffic, the best one depends on the level of detail you need to retain and what sort of additional equipment you can use to accomplish the monitoring. If you are concerned about the risk of compromise on a system, you should consider forwarding whatever auditing solution you choose to another system that is inaccessible (except for logging) from the one you are monitoring. Successful attackers would likely remove evidence of their breach from the local logging systems.
What's the most effective way to monitor SSH access in Gentoo Linux? My Gentoo box is operating locally behind my broadband router. I have SSH port forwarding on the router and a DNS entry pointing to my router on the internet. Is there a way to silently record what external domain/IP the incoming connection to my Gentoo box comes from? Similarly what's the best method of recording all network traffic to and from this box, again without being noisy about it?
How to transparently monitor SSH access/network traffic in Gentoo/general linux?
You can get byte and packet counts from conntrack. To enable counters, set accounting #sysctl net.netfilter.nf_conntrack_acct=1Then you will see conntrack ouput like this #conntrack -L tcp 6 431971 ESTABLISHED src=192.168.0.156 dst=192.168.0.1 sport=53474 dport=443 packets=11 bytes=1945 src=192.168.0.1 dst=192.168.0.156 sport=443 dport=53474 packets=12 bytes=5238 [ASSURED] mark=0 use=1You can zero counters with this command #conntrack -L -zNote that these counters are connection based. Conntrack entry will be removed once connection closed. Check man page for more information #man conntrack
How can I log quantities of IP traffic by src/dst (and port for UDP & TCP)? For each interval (probably each hour) I would like to see something like: proto, src, dst, packets, octets ICMP, 192.168.1.3, 2.3.4.5, 34, 483 TCP, 192.168.1.3:34821, 2.3.4.5:80, 123, 23408 TCP, 192.168.1.3:33812, 5.6.7.8:22, 201, 2039 TCP, 192.168.1.3:53, 1.1.1.1:53, 23, 3400 UDP, 192.168.1.3:53, 1.1.1.1:53, 323, 23403For a gateway/router box, I expect thousands of lines each hour. I know that iptables can count traffic, but as far as I have understood you need to know the addresses and ports before you start counting. Is there a commonly used solution to counting all IP traffic? (I am looking for a low-level tool/technique, not a function of a network management suite.)
How to log quantities of IP traffic by src/dst (and port for UDP & TCP)?
As Christopher said:Does this information help? Maybe not the same scenario, but probably relevant. Separate Network Traffic on Two Network InterfacesThis helped as disabling reverse path filtering solved this issue.
I have a problem on my Redhat computer. I do have incoming traffic on a network interface, let's call it eth1. I also have outgoing traffic on another network interface, let's call it eth2. When the route for outgoing traffic is not set, incoming traffic is correctly received on eth1 (a program is using information contained in this incoming flow), and, obviously, outgoing traffic from eth2 is not correctly routed since the route is not set. When I set the route for eth2, my outgoing traffic is now correctly routed and there is no problem here. But incoming traffic on eth1 is not received anymore! It is very curious because I don't see how a route can block incoming traffic. When using Wireshark on eth1, I see that packets are still received. When using Netcat, nothing is received. If I delete the route, Netcat now receive the incoming traffic and everything works fine, but outgoing eth2 traffic is not routed anymore and I need this packets to be routed. Is there a route mechanism I don't understand?
Route blocking incoming traffic
You simply provide all the patterns to the -I command, separated by |. From the manpage: -P pattern List only those files that match the wild-card pattern. Note: you must use the -a option to also consider those files begin‐ ning with a dot `.' for matching. Valid wildcard operators are `*' (any zero or more characters), `?' (any single character), `[...]' (any single character listed between brackets (optional - (dash) for character range may be used: ex: [A-Z]), and `[^...]' (any single character not listed in brackets) and `|' separates alternate patterns.-I pattern Do not list those files that match the wild-card pattern.So, for example tree -I 'test*|docs|bin|lib'skips the 'docs', 'bin', and 'lib', directories, and any directory with 'test' in the name, wherever they may lie within the directory hierarchy. Obviously, you can apply wildcards for much more powerful matching.
I need to print the directory structure of our production system and I would like to remove some specific directories from the tree? How do we specify multiple ignore patterns for tree command?
How do we specify multiple ignore patterns for `tree` command?
Only for tree 1.6 and above You might want to look at: man tree--du For each directory report its size as the accumulation of sizes of all its files and sub-directories (and their files, and so on). The total amount of used space is also given in the final report (like the 'du -c' command.) This option requires tree to read the entire directory tree before emitting it, see BUGS AND NOTES below. Implies -s.So you should use: tree --du -h
I like tree it's a nice way to display my files and the size of folders/directories. But the -h option only shows the size of the directory, not the cumulative size of its contents. /media/ β”œβ”€β”€ [ 16K] 64D9-E862 β”‚ β”œβ”€β”€ [8.0K] downloadsI know for a fact that my external drive has more that 16kB in it. How can I fix that with tree 1.5? Better yet how do I upgrade to 1.6?
Print size of directory content with tree command in tree 1.5?
I'm not sure about this but I think all you need is tree | sed 's/β”œ/\+/g; s/─/-/g; s/β””/\\/g'For example: $ tree . β”œβ”€β”€ file0 └── foo β”œβ”€β”€ bar β”‚ └── file2 └── file12 directories, 3 files $ tree | sed 's/β”œ/\+/g; s/─/-/g; s/β””/\\/g' . +-- file0 \-- foo +-- bar β”‚ \-- file2 \-- file12 directories, 3 filesAlternatively, you can use the --charset option: $ tree --charset=ascii . |-- file0 `-- foo |-- bar | `-- file2 `-- file12 directories, 3 files
The "tree" command uses nice box-drawing characters to show the tree but I want to use the output in a "code-page-neutral" context (I know that really there's always a code page, but by restricting it to the lower characters I hope to be free of worries that someone in Ulan Bator sees smiley faces, etc). For example instead of: β”œβ”€β”€ include β”‚ β”œβ”€β”€ foo β”‚ └── barI'd like something like: +-- include | +-- foo | \-- barbut none of the "tree" switch combinations I tried gave this (seems more as if they take the box-drawing chars as the baseline and make it yet prettier) I also looked for box-drawing filters to perform such conversions without finding anything beyond an infinite amount of ASCII art :-). A generic filter smells like something to be cooked-up in 15 mins - plus two more incremental days stumbling into all the amusing corner cases :-)
"tree" command output with "pure" (7-bit) ASCII output
try: find . -type f -exec cat {} +
I want to cat a file in current folder and all files in all subfolders (and subsubfolders). Here is my directory structure $ tree . β”œβ”€β”€ f β”‚ └── foo └── yoI want to cat foo and yo. I've tried this command but did not work: cat */*It just cats foo.
cat files in current folder and all subfolders [duplicate]
Also checkout ncdu: http://dev.yorhel.nl/ncdu Its page also lists other "similar projects":gt5 - Quite similar to ncdu, but a different approach. tdu - Another small ncurses-based disk usage visualization utility. TreeSize - GTK, using a treeview. Baobab - GTK, using pie-charts, a treeview and a treemap. Comes with GNOME. GdMap - GTK, with a treemap display. Filelight - KDE, using pie-charts. QDirStat - KDE, with a treemap display. QDiskUsage - Qt, using pie-charts. xdiskusage - FLTK, with a treemap display. fsv - 3D visualization. Philesight - Web-based clone of Filelight.
I'm wondering if we can combine the honesty of 'du' with the indented formatting of 'tree'. If I want a listing of the sizes of directories: du -hx -d2...displays two levels deep and all the size summaries are honest, but there's no indenting of subdirs. On the other hand: tree --du -shaC -L 2...indents and colorizes nicely however the reported sizes are a lie. To get the real sizes one must: tree --du -shaC...which is to say that you only get the true sizes if you let 'tree' show you the entire directory structure. I'd like to be able to always have correct size summaries regardless of how many levels of subdirs I want to actually display. I often do this: tree -du -shaC | grep "\[01;34m"... which prunes out everything but directories, and indents them nicely ... but there's no easy way to limit the display to just a given number levels (without the summaries lying). Is there a way? Perhaps I've missed the correct switches ...
combine the best of 'du' and 'tree'
This might help: list git ignored files in an almost-compatible way for tree filter: function tree-git-ignore { # tree respecting gitignore local ignored=$(git ls-files -ci --others --directory --exclude-standard) local ignored_filter=$(echo "$ignored" \ | egrep -v "^#.*$|^[[:space:]]*$" \ | sed 's~^/~~' \ | sed 's~/$~~' \ | tr "\\n" "|") tree --prune -I ".git|${ignored_filter: : -1}" "$@" }
Is there a way to make tree not show files that are ignored in .gitignore?
Have tree hide gitignored files
You want the -R switch to less. From the less man page:-R or --RAW-CONTROL-CHARS Like -r, but only ANSI "color" escape sequences are output in raw" form. Unlike -r, the screen appearance is maintained correctly in most cases. ANSI "color" escape sequences are sequences of the form: ESC [ ... mSo you need tree -C public/ | less -R
I get colored tree using tree -C but when I pipe it to less I get results like this: tree public/ -C | lessHow can I have colors in less in this case?
How can I pipe colored tree result to less or more?
As others have said in the comments, listing only non-directories doesn't exactly mesh with the purpose of the tree command. However, listing only the files in the current directory is not unusual if you're like me and prefer to use a customized tree over ls (and maybe you've even aliased ls to tree with your preferred flags and arguments). Leveraging a combination of tree and grep will get you what you want: $ tree -F . β”œβ”€β”€ file1.txt β”œβ”€β”€ file5.txt β”œβ”€β”€ parent_dir1/ β”‚ β”œβ”€β”€ child_dir/ β”‚ β”œβ”€β”€ file2.txt β”‚ └── file3.txt └── parent_dir2/ └── child_dir2/ └── file4.txt4 directories, 4 files $ tree -FL 1 | grep -v /$ . β”œβ”€β”€ file1.txt β”œβ”€β”€ file5.txt2 directories, 1 fileThe 'F' flag causes tree to append a '/' to directories, and the 'v' flag to grep inverts the given pattern, which matches all lines ending in '/'. You'll notice that even the summary at the end is still applicable, despite the fact that the directories aren't actually being displayed. Once you go more than one level down, the tree structure dominates and things get a bit weird. $ tree -FL 3 | grep -v /$ . β”œβ”€β”€ file1.txt β”œβ”€β”€ file5.txt β”‚ β”œβ”€β”€ file2.txt β”‚ └── file3.txt └── file4.txt4 directories, 4 filesEDIT Also, if the sort of broken tree output bothers you (i.e. the fact that some files are prefaced by the 'β”œβ”€' character instead of the '└─' character, and the multi-level version just seems to trail off...), you can fix this by sorting the output, directories first. $ tree --dirsfirst -FL 1 | grep -v /$ . β”œβ”€β”€ file1.txt └── file5.txt2 directories, 1 file $ tree --dirsfirst -FL 3 | grep -v /$ . β”‚ β”œβ”€β”€ file2.txt β”‚ └── file3.txt β”‚ └── file4.txt β”œβ”€β”€ file1.txt └── file5.txt 4 directories, 5 filesI think this actually makes the node-less tree structure more readable, as well.
tree has a -d option to "List directories only.". However, I cannot seem to find an option to "List files only." I have looked through the man page, but I cannot seem to find an option for listing only files.
How to make tree output only files?
Attempt 1 A solution using just perl, returning a simple hash of hashes structure. Before the OP clarified data format of JSON. #! /usr/bin/perluse File::Find; use JSON;use strict; use warnings;my $dirs={}; my $encoder = JSON->new->ascii->pretty;find({wanted => \&process_dir, no_chdir => 1 }, "."); print $encoder->encode($dirs);sub process_dir { return if !-d $File::Find::name; my $ref=\%$dirs; for(split(/\//, $File::Find::name)) { $ref->{$_} = {} if(!exists $ref->{$_}); $ref = $ref->{$_}; } }File::Find module works in a similar way to the unix find command. The JSON module takes perl variables and converts them into JSON. find({wanted => \&process_dir, no_chdir => 1 }, ".");Will iterate down the file structure from the present working directory calling the subroutine process_dir for each file/directory under ".", and the no_chdir tell perl not to issue a chdir() for each directory it finds. process_dir returns if the present examined file is not a directory: return if !-d $File::Find::name;We then grab a reference of the existing hash %$dirs into $ref, split the file path around / and loop with for adding a new hash key for each path. Making a directory structure like slm did: mkdir -p dir{1..5}/dir{A,B}/subdir{1..3}The output is: { "." : { "dir3" : { "dirA" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} }, "dirB" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} } }, "dir2" : { "dirA" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} }, "dirB" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} } }, "dir5" : { "dirA" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} }, "dirB" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} } }, "dir1" : { "dirA" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} }, "dirB" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} } }, "dir4" : { "dirA" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} }, "dirB" : { "subdir2" : {}, "subdir3" : {}, "subdir1" : {} } } } }Attempt 2 Okay now with different data structure... #! /usr/bin/perluse warnings; use strict; use JSON;my $encoder = JSON->new->ascii->pretty; # ascii character set, pretty format my $dirs; # used to build the data structuremy $path=$ARGV[0] || '.'; # use the command line arg or working dir# Open the directory, read in the file list, grep out directories and skip '.' and '..' # and assign to @dirs opendir(my $dh, $path) or die "can't opendir $path: $!"; my @dirs = grep { ! /^[.]{1,2}/ && -d "$path/$_" } readdir($dh); closedir($dh);# recurse the top level sub directories with the parse_dir subroutine, returning # a hash reference. %$dirs = map { $_ => parse_dir("$path/$_") } @dirs;# print out the JSON encoding of this data structure print $encoder->encode($dirs);sub parse_dir { my $path = shift; # the dir we're working on # get all sub directories (similar to above opendir/readdir calls) opendir(my $dh, $path) or die "can't opendir $path: $!"; my @dirs = grep { ! /^[.]{1,2}/ && -d "$path/$_" } readdir($dh); closedir($dh); return undef if !scalar @dirs; # nothing to do here, directory empty my $vals = []; # set our result to an empty array foreach my $dir (@dirs) { # loop the sub directories my $res = parse_dir("$path/$dir"); # recurse down each path and get results # does the returned value have a result, and is that result an array of at # least one element, then add these results to our $vals anonymous array # wrapped in a anonymous hash # ELSE # push just the name of that directory our $vals anonymous array push(@$vals, (defined $res and scalar @$res) ? { $dir => $res } : $dir); } return $vals; # return the recursed result }And then running the script on the proposed directory structure... ./tree2json2.pl . { "dir2" : [ "dirB", "dirA" ], "dir1" : [ "dirB", { "dirA" : [ "dirBB", "dirAA" ] } ] }I found this pretty damn tricky to get right (especially given the "hash if sub directories, array if not, OH UNLESS top level, then just hashes anyway" logic). So I'd be surprised if this was something you could do with sed / awk ... but then Stephane hasn't looked at this yet I bet :)
Is there a convenient way to convert the output of the *nix command tree to JSON format? My goal is to convert something like: . |-- dir1 | |-- dirA | | |-- dirAA | | `-- dirBB | `-- dirB `-- dir2 |-- dirA `-- dirBinto: {"dir1" : [{"dirA":["dirAA", "dirAB"]}, "dirB"], "dir2": ["dirA", "dirB"]}
Convert output of tree command to json format
I haven't tried it, but using -I and -X could give you what you want. My first tries would be along the line of wget -m -I bar1/bar2 -X "*" http://www.foo.com/bar1/bar2/bar3/index.htmlExplanation of options: -m: --mirror Turn on options suitable for mirroring. This option turns on recursion and time-stamping, sets infinite recursion depth and keeps FTP directory listings. It is currently equivalent to -r -N -l inf --no-remove-listing. -I: list --include-directories=list Specify a comma-separated list of directories you wish to follow when downloading. Elements of list may contain wildcards. -X: list --exclude-directories=list Specify a comma-separated list of directories you wish to exclude from download. Elements of list may contain wildcards.
wget has such option as -np which disables getting files from any parent directory. I need something similar but a bit more flexible. Consider: www.foo.com/bar1/bar2/bar3/index.htmlI would like to get everything but not "higher" (in the tree hierarchy) than bar2 (!). So bar2 should also be fetched but not bar1. Is there a way to make wget more selective? Background: I'm trying to mirror a website, with a similar logical structure -- starting point, then up, then down. If there is another tool than wget, better suited for such layout, please let me know as well. Update Or instead of specifying possible depth up, maybe something like "no parents, unless they match this or that URL". Update 2 There is some structure on the server, right? You can visualize it as a tree. So normally with "--no-parent" you start from some point A and go only down. My wish, is ability to go up -- expressed by saying, it is allowed to go up X nodes, or (which is 100% equivalent) that it is allowed to go up to B node (where the distance B-A=X). In all cases, the rules for going down stays as were defined by users (for examples -- go down only by Y levels). How to store it? Actually it is not the question really -- wget by default recreates the server structure, there is nothing here to be afraid, or there is no need for fixing anything. So, in 2 words -- as usual. Update 3 Directory structure below -- let's assume that in each directory there is only one file, in R -- R.html and so on. This is simplified of course because you can have more than one page. R / \ B G / \ C F / \ A D / E A (A.html) is my starting point, X = 2 (so B is the most top level node I would like to fetch). In this particular example this means fetching all pages except R.html and G.html. A.html is called "starting point" because I have to start from it, not from B. Update 4 Naming is used from Update 3.wget OPTIONS www.foo.com/B/C/A/A.htmlThe question is what are the options to get all pages from directory B and below (knowing that you have to start from A.html).
Is there a way to disable wget from getting files from parent directories to given depth?
The nerdtree plugin for vim should do just that. It gives you a tree view of your filesystem inside vim that can be used interactively. It supports a dozen features such as bookmarking files, syntax highlighting, mouse support, tree filtering and more. Generally, good stuff to have when working on projects that span multiple files and directories.
Is there any version of tree command that displays file structure as a tree structure, but in a way that I can interactively walk trough? Why do I need it exactly - I am trying to simulate TextMate project drawer using vim and splitscreen with screen and "interactive" tree on the left. But if there is any better way than that, I would also like to hear it.
Interactive tree command
So you want something like this: tree | sed 's/β”œ\|─\|β”‚\|β””/ /g'It replaces all those "line" characters with spaces.See: $ tree . β”œβ”€β”€ dir1 β”‚ β”œβ”€β”€ file1 β”‚ └── file2 └── dir2 β”œβ”€β”€ file1 └── file22 directories, 4 files $ tree | sed 's/β”œ\|─\|β”‚\|β””/ /g' . dir1 file1 file2 dir2 file1 file22 directories, 4 files
I want to list the subdirectories of a directory using tree command. But I don't want to print indentation lines. I only want to have the whitespaces instead. I couldn't find the correct parameter in man page. Maybe I can pipe the output of tree to sed to remove the lines.
Print indentations with whitespace only in tree command
I found the answer after I posted an issue on Oh-My-Zsh's repository. Color in tree rely on LS_COLORS, which is not set by Zsh by default; but my ~/.zshrc set the variable after I hit "use default setting" option, with a single line eval "$(dircolors -b)"which looks insignificant. After installing Oh-My-Zsh, the setting is moved to ~/.zshrc.pre-oh-my-zsh, so LS_COLORS is lost again, and my tree becomes black and white. In other words, I moved that setting from ~/.zshrc.pre-oh-my-zsh back to .zshrc, and I am now with my colorful tree.
In plain zsh, tree is set similar to --color=auto by default. However, when I use Oh-My-Zsh, tree doesn't show colors. Since tree does not have a --color=auto option, how can I override the setting back to the auto one?
Automatically colorize the output of tree
To append trailing slashes for directories, simply revise your code to include the -F option, in _tree.sh: tree -F -L 2 --charset ascii -I "_tree.sh|LICENSE|README.md|node_modules|nbproject"Explanation The tree program (for example version 1.7.0) does not append trailing slashes by default. As @steeldriver points out, it may only be due to -F option enabled somewhere on your system, such as within ~/.bashrc or ~/.bash_aliases defined as an alias, that makes it so you see trailing slashes when you run tree on the terminal. To have trailing slashes in your scripts too, simply add -F option to your tree command.
I have a shell script executes tree command $ cat _tree.sh #!/bin/sh tree -L 2 --charset ascii -I "_tree.sh|LICENSE|README.md|node_modules|nbproject" $ sh _tree.sh . |-- bower.json |-- dpl |-- dst |-- gulpfile.js |-- package.json `-- src |-- fonts |-- images |-- scripts `-- styles7 directories, 3 files $When I execute the command directly, $ tree -L 2 --charset ascii -I "_tree.sh|LICENSE|README.md|node_modules|nbproject" . |-- bower.json |-- dpl/ |-- dst/ |-- gulpfile.js |-- package.json `-- src/ |-- fonts/ |-- images/ |-- scripts/ `-- styles/7 directories, 3 files $The forwarding slashes(/) are appended. How can I make the _tree.sh file do this?
tree command in a shell script doesn't append slashes for directories
find . -type d | \ perl -ne 'BEGIN{ sub cnt{ $file=shift; $c="find $file -maxdepth 1 -type f | wc -l";int(`$c`) }} chomp; printf "%s %s\n", $_, cnt($_)' | \ perl -ne '/^(.*) (\d*)$/; $_{scalar(split /\//, $1)}+=$2; END { printf "Depth %d has %d files.\n", @$_ for map { [$_,$_{$_}] } sort keys %_ }'Results: Depth 1 has 7 files. Depth 2 has 2353 files. Depth 3 has 2558 files. Depth 4 has 8242 files. Depth 5 has 6452 files. Depth 6 has 674 files. Depth 7 has 1112 files. Depth 8 has 64 files. Depth 9 has 154 files.
I need to look into a particular directory and list the number of files per level. The directory is pretty large, about 10-15 levels deep. For instance, if I have the following: D1 | |-- D2A (5 files in this directory) | |-- D3A (6 files in this directory) | |-- D3B (7 Files in this directory) | |-- D2B (1 file in this directory)Then it should tell me that level 3 has 13 files and level 2 has 6 files (or 6+13, doesn't matter). Can Tree accomplish this? I've tried around mixing the options but it does not seem to work.
Can tree be used to list the number of files per level?
Yes, it's a bug. From man page: BUGS Tree does not prune "empty" directories when the -P and -I options are used. Tree prints directories as it comes to them, so cannot accumu‐ late information on files and directories beneath the directory it is printing.... at all, -d switch ask to not print files: -d List directories only.So if you WANT use this, you could: tree tstdir -P '*qm*' -L 1 | grep -B1 -- '-- .*qm' |-- id1 | `-- aqm_P1800-id1.0200.bin -- |-- id165 | `-- aqm_P1800-id165.0200.bin |-- id166 | `-- aqm_P1800-id166.0200.bin -- |-- id17 | `-- aqm_P1800-id17.0200.bin -- |-- id18 | `-- aqm_P1800-id18.0200.bin -- |-- id2 | `-- aqm_P1800-id2.0200.binAt all, if you use -L 1, -L level Max display depth of the directory tree.you could better use (in bash) this syntax: cd tstdir echo */*qm*or printf "%s\n" */*qm*and if only dir is needed: printf "%s\n" */*qm* | sed 's|/.*$||' | uniqAt all, you could do this very quickly if pure bash: declare -A array;for file in */*qm* ;do array[${file%/*}]='';done;echo "${!array[@]}"This could be explained: cd tstdir declare -A array # Declare associative array, (named ``array'') for file in */*qm* ;do # For each *qm* in a subdirectory from there array[${file%/*}]='' # Set a entry in array named as directory, containing nothing done echo "${!array[@]}" # print each entrys in array.... if there is no file matching pattern, result would display *. so for perfect the job, there left to do: resultList=("${!array[@]}") [ -d "$resultList" ] || unset $resultList(This would be a lot quicker than declare -A array for file in */*qm*; do [ "$file" == "*/*qm*" ] || array[${file%/*}]='' done echo "${!array[@]}")
I'm trying to figure out if there is a way to get the UNIX command tree to display only directories that match a specific pattern. % tree -d tstdir -P '*qm*' -L 1 tstdir |-- d1 |-- d2 |-- qm1 |-- qm2 `-- qm35 directoriesThe man page shows this bit about the switch.-P pattern List only those files that match the wild-card pattern. Note: you must use the -a option to also consider those files beginning with a dot .' for matching. Valid wildcard operators are*' (any zero or more characters), ?' (any single character),[...]' (any single character listed between brackets (optional - (dash) for character range may be used: ex: [A-Z]), and [^...]' (any single character not listed in brackets) and|' sepa‐ rates alternate patterns.I'm assuming that the bit about ...List only those files... is the issue. Am I correct in my interpretation that this switch will only pattern match on files and NOT directories? EDIT #1 @f-hauri looks to have the best reason as to why this doesn't work the way one would think from the switches available in the tree man page. I missed this bit in the BUGS section. BUGS Tree does not prune "empty" directories when the -P and -I options are used. Tree prints directories as it comes to them, so cannot accumu‐ late information on files and directories beneath the directory it is printing.Given this limitation it looks like tree isn't the best way to accomplish an inclusive filtered list, but a exclusive filtered list would be an alternative way using the -I switch. In lieu of this it would look like either shell wildcards, the find command, or a Perl script would be a more appropriate way to accomplish this. See @f-hauri's fine answer for some of these alternative methods.
Can the UNIX command tree display only directories matching a pattern?
It requires special box-drawing characters, as commented by another user. In the terminal, it is possible to call them via the printf command. For example, to recreate the first two lines of the tree example in the question, it would look like: printf "\x1b(0\x74\x1b(B\x1b(0\x71\x1b(B\x1b(0\x71\x1b(B info\n" printf "\x1b(0\x78\x1b(B \x1b(0\x6d\x1b(B\x1b(0\x71\x1b(B\x1b(0\x71\x1b(B exclude\n"For a list of the box-drawing characters, see the wikipedia page.
I've been searching for this for a while and didn't get a satisfactory answer for it. I've taken this screenshot from the output of Gnu/Linux's tree command.I want to know how to draw or print lines like these, I've tried reading the source code of the tree program but didn't understand anything.
How to draw a continuous line in terminal?
tree versions 1.7.0 and 1.8.0 didn’t take --du into account when sorting by size: directories were sorted by their own size, not the size of their contents. This was fixed in version 2.0.0.
I'm trying to sort by size: % tree -axCF --du --sort=size | grep -e '/$' β”œβ”€β”€ [ 8658884] 2022-10-09-backup/ β”œβ”€β”€ [ 5923934] f24-01-22-backup/ β”œβ”€β”€ [ 5384825] e2023-01-19-backup/ β”œβ”€β”€ [ 3627525] h24-01-22-npanelize-nselect/ β”œβ”€β”€ [ 2162140] b2022-12-18-backup/ β”œβ”€β”€ [ 1255661] a2022-12-12-backup/ β”œβ”€β”€ [ 996252] 2021-08-12-backup/ β”œβ”€β”€ [ 647677] 2022-11-20-backup/ β”œβ”€β”€ [ 133361] Test/ β”œβ”€β”€ [ 95801] Boneyard/ β”œβ”€β”€ [ 1024] g24-01-22-backup/ < Ooops β”œβ”€β”€ [ 16031] Misc/ β”œβ”€β”€ [ 1024] Temp/ < Ooops β”œβ”€β”€ [ 449317] Znt/ β”‚ β”œβ”€β”€ [ 158892] Boneyard/ β”‚ └── [ 199717] VirginN-functions/ β”‚ β”œβ”€β”€ [ 34739] backup.1/ < Nothing right in this dir β”‚ β”œβ”€β”€ [ 29896] Source/ β”‚ β”œβ”€β”€ [ 35481] Text/ β”‚ └── [ 98577] virgin/... as we see, it's not too bad, however there are a few anomalies. Is there some reason for this? Can I do anything about it? BTW the 'grep' is because, AFAICT, 'tree' won't show you directory content sizes, even if you use '--du', unless you show all files too (you can't use '-d'), and since I don't want to show files I use grep to filter them out. This seems weird, but thereyago.
tree command with 'sort=size' seems imperfect
The basic problem is that watch and tree use different information for getting the colors:The watch program interprets standard (ECMA-48) escape sequences for specifying video attributes. That means 8 colors, plus bold, blink, underline, reverse and italics. It uses (n)curses to display the information, making the result depend on the terminal database The tree program mimics GNU ls, using the LS_COLORS environment variable. That uses the TERM environment variable (which curses and most other terminal applications use to identify an entry in the terminal database) to select a set of customized escape sequences, which do not necessarily have any relationship to the terminal database's descriptions.With some work, you could make those match, e.g., by generating a suitable LS_COLORS for a given terminal entry. Apparently no one has done that. And since the contents of LS_COLORS incomplete (covering only a small fraction of a terminal description: no function keys, no cursor movement, no generality), there is no point in generating a terminal entry from LS_COLORS. If tree uses 256 colors, watch may not understand those codes (a recent change addresses a part of this issue for procps top but has not been adapted for watch β€” wait a while). watch uses (n)curses to manage the screen, which makes it necessary (for watch) to translate escape-codes into curses-calls. Further reading:How do I get color with VT100? Applications miscited as library users The Tree Command for Linux Homepage procps (watch development)
I am using a simple combination of commands to "monitor" a bit of my filesystem change: watch and tree. Except I want colours and can't get it. Here's what I thought should work: watch --color 'tree -C' which kind of works since it gives me some colours, but not in the same way as tree -C by itself. Here's some screencaps: watch --color 'tree -C' output, with some colours applying watch 'tree -C' output, showing that tree does indeed send all escape codes tree -C output, expected result Culprit might also be in my env variables, but if I watch 'echo $LS_COLORS', my conf is there. Any ideas? :)
tree(1) colours not properly interpeted by watch(1) even with --color option
Someone mentioned on stackoverflow in the trees man page that this is why the -P switch doesn't exclude things that don't match the pattern. BUGS Tree does not prune "empty" directories when the -P and -I options are used. Tree prints directories as it comes to them, so cannot accumu‐ late information on files and directories beneath the directory it is printing.So it doesn't appear to be possible to get tree to filter its output using the -P switch. EDIT #1 From a question I had posted on SO that got closed. Someone, @fhauri, had posted the following information as alternative ways to accomplish what I was trying to do with the tree command. I'm adding them to my answer here for completeness. -d switch ask to not print files: -d List directories only.So if you WANT use this, you could: tree tstdir -P '*qm*' -L 1 | grep -B1 -- '-- .*qm' |-- id1 | `-- aqm_P1800-id1.0200.bin -- |-- id165 | `-- aqm_P1800-id165.0200.bin |-- id166 | `-- aqm_P1800-id166.0200.bin -- |-- id17 | `-- aqm_P1800-id17.0200.bin -- |-- id18 | `-- aqm_P1800-id18.0200.bin -- |-- id2 | `-- aqm_P1800-id2.0200.binAt all, if you use -L 1, -L level Max display depth of the directory tree.you could better use (in bash) this syntax: cd tstdir echo */*qm*or printf "%s\n" */*qm*and if only dir is needed: printf "%s\n" */*qm* | sed 's|/.*$||' | uniqAt all, you could do this very quickly if pure bash: declare -A array;for file in */*qm* ;do array[${file%/*}]='';done;echo "${!array[@]}"This could be explained: cd tstdir declare -A array # Declare associative array, (named ``array'') for file in */*qm* ;do # For each *qm* in a subdirectory from there array[${file%/*}]='' # Set a entry in array named as directory, containing nothing done echo "${!array[@]}" # print each entrys in array.... if there is no file matching pattern, result would display *. so for perfect the job, there left to do: resultList=("${!array[@]}") [ -d "$resultList" ] || unset $resultList(This would be a lot quicker than declare -A array for file in */*qm*; do [ "$file" == "*/*qm*" ] || array[${file%/*}]='' done echo "${!array[@]}")
I'm trying to figure out if there is a way to get the UNIX command tree to display only directories that match a specific pattern. % tree -d tstdir -P '*qm*' -L 1 tstdir |-- d1 |-- d2 |-- qm1 |-- qm2 `-- qm35 directoriesThe man page shows this bit about the switch.-P pattern List only those files that match the wild-card pattern. Note: you must use the -a option to also consider those files beginning with a dot .' for matching. Valid wildcard operators are*' (any zero or more characters), ?' (any single character),[...]' (any single character listed between brackets (optional - (dash) for character range may be used: ex: [A-Z]), and [^...]' (any single character not listed in brackets) and|' sepa‐ rates alternate patterns.I'm assuming that the bit about ...List only those files... is the issue. Am I correct in my interpretation that this switch will only pattern match on files and NOT directories?
Can the UNIX command tree display only directories matching a pattern?
Since tree does not read stdin, but instead traverses the actual directory structure (whether the current directory or the specified directories), you would need to post-process the table of contents of the tar file. If the tar file was created with full/absolute path names, you'll need to adjust the ranges to find your desired directory depth. One option is awk: tar -tf tarfile | awk -F/ 'NF == 3'Another is cut (sorting uniquely so that child directories beyond level 2 don't cause the parent to be reported again): tar -tf tarfile | cut -d/ -f1-3 | sort -u
I would like to see the tree of a big compressed file (specifically only the second level of directories) so I used the following command:tar -tf tarfile | tree -L 2But it outputs the tree of the directory I am in, not of the compressed file. The other commands work fine, for example if I do:tar -tf tarfile | lessIt lets me explore correctly the tarfile. Am I doing something wrong or I can't use tree like other commands trough pipping? If not, is there any other way to only see the files till second level directories of a compressed file?
pipe of tar and tree commands?
I think tree normally needs to print the directory name to get the tree-like structure. How about using find instead? find dir/ -type fwith above command you can get all and only files (-type f) recursively. It displays with path of the file, though. In case that you don't want to display the path of the file, you can apply basename command at the end, like this: find dir/ -type f -exec basename {} \;
I've read through the man pages for tree but I don't know if it is possible to have tree list only the filenames for all files that appear in any recursive search of a directory. The closest I have gotten is: tree -i --noreport dir/ which might give me something like: ./lib order crossCount.js rank acyclic.jsWhere order, lib, and rank are directories that I do not want listed.
Getting tree command to not display directories
tree behaves that way because it doesn’t dereference symlinks by default. The -l option will change that: tree -l /sys/class/hwmon/but you’ll have fun making sense of all the output.
If I understand correctly, in Linux, everything is a path, right down to each piece of hardware. I am trying to get information about how my sensors are structured, so I thought I would just use tree to map out all the things in my hwmon directory. However, tree does not behave the same with this directory as I am accustomed to. When I run tree on a normal directory, I get the subdirectory structure without using the -R or -L flags: $ tree /home /home └── boss β”œβ”€β”€ clones β”œβ”€β”€ Desktop β”œβ”€β”€ Documents β”‚ β”œβ”€β”€ modules.txt β”‚ β”œβ”€β”€ old_docs β”‚ β”‚ └── assorted β”‚ └── prepscript.txt β”œβ”€β”€ Downloads β”œβ”€β”€ Music β”œβ”€β”€ Pictures β”œβ”€β”€ Public β”œβ”€β”€ Templates └── Videos12 directories, 2 filesbut I try to do the same with HWmon, it only goes one level deep, even if I do use the -R flag and even though there is stuff deeper: $ tree /sys/class/hwmon/ /sys/class/hwmon/ β”œβ”€β”€ hwmon0 -> ../../devices/pci0000:40/0000:40:01.3/0000:43:00.0/hwmon/hwmon0 β”œβ”€β”€ hwmon1 -> ../../devices/pci0000:00/0000:00:01.3/0000:09:00.0/hwmon/hwmon1 β”œβ”€β”€ hwmon2 -> ../../devices/pci0000:40/0000:40:03.1/0000:44:00.0/hwmon/hwmon2 β”œβ”€β”€ hwmon3 -> ../../devices/pci0000:00/0000:00:18.3/hwmon/hwmon3 β”œβ”€β”€ hwmon4 -> ../../devices/pci0000:00/0000:00:19.3/hwmon/hwmon4 β”œβ”€β”€ hwmon5 -> ../../devices/virtual/thermal/thermal_zone0/hwmon5 └── hwmon6 -> ../../devices/platform/nct6775.656/hwmon/hwmon67 directories, 0 files $ tree /sys/class/hwmon/hwmon0 /sys/class/hwmon/hwmon0 β”œβ”€β”€ device -> ../../../0000:43:00.0 β”œβ”€β”€ fan1_input β”œβ”€β”€ name β”œβ”€β”€ power β”‚ β”œβ”€β”€ async β”‚ β”œβ”€β”€ autosuspend_delay_ms β”‚ β”œβ”€β”€ control β”‚ β”œβ”€β”€ runtime_active_kids β”‚ β”œβ”€β”€ runtime_active_time β”‚ β”œβ”€β”€ runtime_enabled β”‚ β”œβ”€β”€ runtime_status β”‚ β”œβ”€β”€ runtime_suspended_time β”‚ └── runtime_usage β”œβ”€β”€ pwm1 β”œβ”€β”€ pwm1_enable β”œβ”€β”€ pwm1_max β”œβ”€β”€ pwm1_min β”œβ”€β”€ subsystem -> ../../../../../../class/hwmon β”œβ”€β”€ temp1_auto_point1_pwm β”œβ”€β”€ temp1_auto_point1_temp β”œβ”€β”€ temp1_auto_point1_temp_hyst β”œβ”€β”€ temp1_crit β”œβ”€β”€ temp1_crit_hyst β”œβ”€β”€ temp1_emergency β”œβ”€β”€ temp1_emergency_hyst β”œβ”€β”€ temp1_input β”œβ”€β”€ temp1_max β”œβ”€β”€ temp1_max_hyst β”œβ”€β”€ uevent └── update_interval3 directories, 27 filesWhat causes this difference in behavior, and can I just get a simple tree of all the devices?
Why can't tree fully list /sys/class/hwmon? And how could I do that?
You can do that with find: find . -mindepth 1 -type d -exec touch "{}/README" \;Explanation-mindepth 1 will set the minimum depth, to avoid including the current directory -type d will only find directories -exec will run a command {} contains the path of the found directoryIf you want to use only builtin shell commands: for dir in *; do if [ -d "$dir" ]; then touch "$dir/README"; fi; doneExplanationfor will loop over every element in *, meaning all files in the current directory. dir will contain the current element during the loop. if [ -d $dir ] checks if the element is a directory and only then creates a file called README in the directory name contained in $dir
For the following tree structure: . └── dir1 └── dir2 └── dir3What would be a simple way to create a file (could be empty), for every directory, so the resulting tree will look like: . β”œβ”€β”€ dir1 β”‚ β”œβ”€β”€ dir2 β”‚ β”‚ β”œβ”€β”€ dir3 β”‚ β”‚ β”‚ └── README β”‚ β”‚ └── README β”‚ └── README └── README
How to create a file for every directory on a tree?
Developed a oneliner for this: $ apt-rdepends --dot -r systemd | perl -ne 'our %chains; if(m!"([^"]+)" -> "([^"]+)"[^"]*;!) { my $c="$2 $chains{$2}"; $chains{$1}=$c; print "$1 $c\n" }' | grep '^monodevelop ' Reading package lists... Done Building dependency tree Reading state information... Done monodevelop libgnome2.24-cil libgnomeui-0 libbonoboui2-0 libgnome2-0 gvfs gvfs-daemons udisks2 libpam-systemd systemd
For example, I want to find out why monodevelop does depend on systemd. apt-rdepends -r systemd shows all packages that that directly or indirectly depend on systemd: $ apt-rdepends --dotty -r systemd | grep monodevelop "monodevelop" -> "libgnome2.24-cil"; ...debtree monodevelop shows all packages monodevelop depend on, directly or indirectly: $ debtree monodevelop | grep -- '-> "systemd"' "libpam-systemd" -> "systemd" [color=blue,label="(= 215-6)"]; ...But how do I easily show the chain from monodevelop to systemd? Example of one of the chains: monodevelop -> libgnome2.24-cil -> libgnome2-0 -> gvfs -> gvfs-daemons -> udisks2 -> libpam-systemd -> systemd
How do I display a dependency chain from one package to another?
Take a look to tree command. http://mama.indstate.edu/users/ice/tree/ For debian like distro : sudo apt-get install tree
Is there a way on unix to print out the file structure, like Bootstrap's getting started page? bootstrap/ β”œβ”€β”€ css/ β”‚ β”œβ”€β”€ bootstrap.css β”‚ β”œβ”€β”€ bootstrap.min.css β”‚ β”œβ”€β”€ bootstrap-theme.css β”‚ β”œβ”€β”€ bootstrap-theme.min.css β”œβ”€β”€ js/ β”‚ β”œβ”€β”€ bootstrap.js β”‚ β”œβ”€β”€ bootstrap.min.js └── fonts/ β”œβ”€β”€ glyphicons-halflings-regular.eot β”œβ”€β”€ glyphicons-halflings-regular.svg β”œβ”€β”€ glyphicons-halflings-regular.ttf └── glyphicons-halflings-regular.woff(from http://getbootstrap.com/getting-started/#whats-included) Is there a command to make it print out exactly like that?
Print out file structure on Unix
Custom tree script treeify.py created by Hakril would help to pretty print contents of tgz without extracting [root@bastion ~]# wget https://bitbucket.org/Hakril/treeify/raw/8e732368f64d30ffc4033cbc890164fdf296d9f8/treeify.py [root@bastion ~]# tar -tvf neo4j-enterprise.tar.gz | python treeify.py . β”œβ”€ drwxrwxrwx root β”‚ β”œβ”€ root 0 2019-05-09 05:05 neo4j-enterprise β”‚ β”‚ └─ local-package β”‚ β”‚ └─ β”‚ └─ root 0 2019-05-15 02:01 neo4j-enterprise β”‚ └─ └─ -rwxr-xr-x root β”œβ”€ root 0 2019-05-09 05:05 neo4j-enterprise β”‚ β”œβ”€ local-package β”‚ β”‚ └─ .sentinel β”‚ └─ .sentinel β”œβ”€ root 10156 2019-05-09 05:05 neo4j-enterprise β”‚ └─ docker-entrypoint.sh └─ root 1560 2019-05-14 21:36 neo4j-enterprise └─ Dockerfile [root@bastion ~]# Ref : https://superuser.com/questions/1086501/list-contents-of-tarball-in-tree-format
I am wondering if it's possible to output the contents of a tar.gz file using tree without having to extract the contents of the file to a temp directory then using tree with that directory. I know we can see the contents of the file without extracting using tar -tf file.tar.gzAnd I have simply tried piping this to the tree command tar -tf file.tar.gz | treeBut this just outputs the tree of the current directory, not the contents of the file. A few questions,Is this even possible? If it is possible, are there any limitations? Depth, number of files, etc? Is there an alternative way to see a tree style output of the contents?
Using tree with tar.gz file without extracting contents
Use awk to convert the structure to "normal" pathes. linux/ linux/audio/ linux/audio/sequenzer/ linux/audio/sequenzer/qtractor/ linux/audio/drummachine/ linux/audio/drummachine/hydrogen/ ...Then you can use tree --fromfile . to read it:convert_structure.awk: { delete path_arr path = "" level=match($0,/[^#]/)-1 sub(/^#*/,"") p[level]=$0 for (l=1;l<=level;l++) { path_arr[l]=p[l] path = path p[l] "/" } print path }RUN: awk -f convert_structure.awk structure.txt | tree --fromfile . --noreportOUTPUT: . └── linux β”œβ”€β”€ audio β”‚ β”œβ”€β”€ drummachine β”‚ β”‚ └── hydrogen β”‚ └── sequenzer β”‚ └── qtractor β”œβ”€β”€ bureau β”‚ β”œβ”€β”€ kalender β”‚ β”‚ └── calcurse β”‚ └── todo β”‚ └── tudu └── scores β”œβ”€β”€ lilypond └── musescoreNotes:Check here if your implementation of awk does not support delete of an array.This works fine with pathes that include spaces, but obviously won't work with pathes inlcuding newlines.
If I have a text-file with a structured list like this: #linux ##audio ###sequenzer ####qtractor ###drummachine ####hydrogen##scores ###lilypond ###musescore##bureau ###kalender ####calcurse ###todo ####tuduHow can I print it tree like to the command-line? linux/ β”œβ”€β”€ audio β”‚ β”œβ”€β”€ drummachine β”‚ β”‚ └── hydrogen β”‚ └── sequenzer β”‚ └── qtractor β”œβ”€β”€ bureau β”‚ β”œβ”€β”€ kalender β”‚ β”‚ └── calcurse β”‚ └── todo β”‚ └── tudu └── scores β”œβ”€β”€ lilypond └── musescoreIs there an application that I'm missing out?
Print structured list to command-line (tree like)
The -R option is only effective in HTML output mode, and is ignored if you don’t also specify a maximum display depth with the -L option. tree -R -L 2 -H . -o tree.htmlwill output the tree to tree.html, and additionally generate subtrees every two levels in OOTree.thml files in each corresponding directory.
So I'm asking myself why there is the "-R" argument for the "tree" command. The manual says "-R Recursively cross down the tree each level directories ...", but I don't see any difference in the result between those two.
Command "tree" vs "tree -R"
Display the directory names first, then jump in and display only filenames: find . ! -name . -type d -print -exec sh -c 'find "$1" -maxdepth 1 ! -type d' {} {} \;
I've been trying to sort output with either tree or find, and end up getting about the same results each time of drilling down to deeper directories before files higher up in the tree. What I'm trying to do is store the directories of interest in a lua table with the directory as the key for sub tables of files. I'm using tree -fi -noreport {Foo,Baz} Foo Foo/Foo.Build.cs Foo/Private Foo/Private/Foos Foo/Private/Foos/Bars Foo/Private/Foos/Bars/BaseBar.cpp Foo/Private/Foo.cpp Foo/Private/FOOPCH.h Baz Baz/Baz.Build.csI want the results to look like: Foo Foo/Foo.Build.cs Foo/Private Foo/Private/Foo.cpp Foo/Private/FOOPCH.h Foo/Private/Foos Foo/Private/Foos/Bars Foo/Private/Foos/Bars/BaseBar.cpp Baz Baz/Baz.Build.cstree fi -noreport {Foo,Baz} | sort -t '/' isn't working. I tried using the solution from this thread, which is tree | awk '{print gsub("/","/"), $0}' | sort -n | cut -d' ' -f2-. If I do that I lose the relationship between directories and files. How can I sort so files at the same depth show up before directories?
List directory hierarchy with files before subdirectories
Distribution A system built on Linux is called a "distribution". Distribution examples:Ubuntu Debian Fedora Arch OpenSuse ...To install a software on a distribution, you have several possibilities:Build the software from source, Install the program with a "package manager".Package manager Almost each distribution use one package manager, most known are:apt-get (debian, ubuntu) pacman (arch) yum (fedora) ...Each package manager has its syntax, type man <package manager>. Build from source It will depends on the software you want to install, but in most cases:get the sources:go to software web page download the source (.tar.gz, .tgz, .zip... file) uncompress itbuild it: # in software source directory ./configure make make install
I tried to install TREE via the sudo apt-get install tree command but nothing but an error happens ("sudo: apt-get: command not found"). How do I fix this?
How do I install TREE when the command line doesn't work?
On Debian, Ubuntu, Mint and other distributions using Dpkg and APT to manipulate packages:dpkg -S /path/to/file looks for the installed package containing the specified file, e.g. dpkg -S /usr/bin/tree dpkg -S $(which tree)apt-file search /path/to/file looks for the package in the distribution containing the specified file, e.g. apt-file search /usr/bin/treeA few commands are built-in, i.e. baked into your shell. Their source code is part of the shell. Use type to find whether a command is built in. $ type cd cd is a shell builtin $ type tree tree is /usr/bin/treeThe command tree is in the package called tree. You can download and unpack the source code for this package with apt-get source tree dpkg-source -x tree_*.dscIn this case, modifying the source code is not the easiest way. It may be a worthwhile exercise if you want to do some C programming. To achieve the objective, using a higher-level language such as Perl, Python or Ruby will be less work.
I'd like to get a custom output from the tree command, but unlike this question, I don't have a fixed format. I'd like to be able to give the command the format in an argument (for instance perhaps -f=y, -f=yaml,-f=xml,-f=~/myformat.fmt). Obviously this is a huge undertaking, but I feel it would be a good way to get to explore how some of the linux commands work under the hood, along with stretching my programming skills. Where should I start if I want to edit (and I presume compile etc) 'native' Linux commands? Are they baked in?
Edit tree to output in custom format?
If you came here looking for this answer (as I did), use: tree --filesfirstOption --filesfirst was added in version 2.0.0 (12/21/2021)
I tried to combine --dirsfirst and -r, but directories still show up on top, only in reverse alphabetical order. It seems like -r is applied first, which is also indicated by the man pages. Any other ideas of how I would go about sorting the output of tree so that subdirectories are listed after the files?
Using `tree`, how do I output files before subdirectories?
Example: $ cat .info a.jpg blah blah blih blih *.jpg jpeg picture $ tree --info . β”œβ”€β”€ a.jpg β”‚ ⎧ blah blah β”‚ ⎩ blih blih β”œβ”€β”€ a.png β”œβ”€β”€ b.jpg β”‚ { jpeg picture β”œβ”€β”€ b.png └── foo.user0 directories, 5 files(with a TAB preceding the comments per the manual you quoted).
man tree1 states:-info Prints file comments found in .info files. See .INFO FILES below for more information on the format of .info files.and further.INFO FILES .info files are similiar to .gitignore files, if a .info file is found while scanning a directory it is read and added to a stack of .info information. Each file is composed of comments (lines starting with hash marks (#),) or wild-card patterns which may match a file relative to the directory the .info file is found in. If a file should match a pattern, the tab indented comment that follows the pattern is used as the file comment. A comment is terminated by a non-tab indented line. Multiple patterns, each to a line, may share the same comment.Objective Given the following directory structure: tree . β”œβ”€β”€ fileA.txt β”œβ”€β”€ fileB.txt └── other_files └── fileC.txtI would like to create a an info file(s) that would enable me to get the following output . β”œβ”€β”€ fileA.txt # Comments on file A read from info file β”œβ”€β”€ fileB.txt # Comments on file B read from info file └── other_files └── fileC.txtFollowing the man pages this should be possible but I can't find an example how such an info file should be created. I've identified one potentially relevant discussion2 but it's not clear to me what should be the structure of this .info file so tree can use it to populate outputs with additional comments.1Version: tree v2.0.2 (c) 1996 - 2022 by Steve Baker, Thomas Moore, Francesc Rocher, Florian Sesser, Kyosuke Tokoro* 2 As discussed in the comments, the link is not pertinent to this question.
Creating .info files to be used with tree
I found a solution using a version of tree which is newer than what was installed on my system. Version 1.8.0 of tree (released 11/16/2018) introduced the --fromfile parameter, which reads a directory/file listing from a file (or stdin) rather than the filesystem itself and generates a tree representation: $ grep -rl 'foobar' ./ |tree --fromfile -F . ./ └── ./ β”œβ”€β”€ dirA/ β”‚ β”œβ”€β”€ dirA.A/ β”‚ β”‚ β”œβ”€β”€ abc.txt β”‚ β”‚ β”œβ”€β”€ def.txt β”‚ β”‚ └── dirA.A.A/ β”‚ β”‚ └── ghi.txt β”‚ └── dirA.B/ β”‚ └── jkl.txt └── dirB/ └── mno.txt6 directories, 5 filesFor reference:http://mama.indstate.edu/users/ice/tree/tree.1.html http://mama.indstate.edu/users/ice/tree/changes.html
I'm searching a large number of text files which are organized in various subdirectories. I can run a command such as grep -lr foobar ./, and I get results like the following: ./dirA/dirA.A/abc.txt ./dirA/dirA.A/def.txt ./dirA/dirA.A/dirA.A.A/ghi.txt ./dirA/dirA.B/jkl.txt ./dirB/mno.txtI would like some way to display these in a visual tree, similar to how the tree command works. Something roughly like this: ./ dirA/ dirA.A/ abc.txt def.txt dirA.A.A/ ghi.txt dirA.B/ jkl.txt dirB/ mno.txtIt seems like it'd be trivial to do this in some Python script with a stack, but I'd really like some way to do this straight from bash if there's a way to do it. So I guess I'm looking for a way to either (a) format/transform the output of grep, OR (b) some other generic "indent-by-common-prefix" utility that I've so-far been unable to find.
Display `grep -lr` results as a tree
You can read about the hash tree index used for directories here.A linear array of directory entries isn't great for performance, so a new feature was added to ext3 to provide a faster (but peculiar) balanced tree keyed off a hash of the directory entry name.
In order to store attachments, a /path/to/atts/ directory will have numerous child-directories (product IDs) created (from 1 to ~10,000 or maybe more in the future), and in each of this subdir, 1 to ~10 attachment files will be created. In /path/to/atts/ 1 β”œβ”€β”€ file1.1 β”œβ”€β”€ file1.2 └── file1.3 2 └── file2.1 ... 10000 β”œβ”€β”€ file10000.1 β”œβ”€β”€ file10000.2 β”œβ”€β”€ file10000.3 β”œβ”€β”€ file10000.4 └── file10000.5(actually 1 .. 10000 was chosen for the sake of a simpler explanation - IDs will be int32 numbers) I'm wondering, on the ext4 file system, what is the cd (actually path resolution) complexity, when reaching /path/to/atts/54321/... for instance:Does the path resolution checks all inode / names one by one in the atts dir until 54321 is reached? Meaning on average n/2 inodes are checked (O(n)) Or is there some tree structure within a dir that reduces the search (e.g. a trie tree, alphabetical order...), that would reduce dramatically the number of inodes checked, like log(n) instead of n/2?If it is the former, I'll change the way the products tree structure is implemented. Just to be clear: the question is not about a find search of a file in a file system tree (that's O(n)). It's actually a path resolution (done by the FS), crossing a directory where thousands of file names reside (the product IDs).
'cd' complexity on ext4
Some time ago I needed to flatten breadth-first the tree of rules of a custom firewall and have them all out on a file. Not VyOS but iptables anyway. I came up with the following script, see if it helps you. Please note that this script requires at least Bash v4 #!/bin/bash -declare -A all_chains=() declare -A queued_chains=()builtin_chains_as_regexp='INPUT|OUTPUT|FORWARD|PREROUTING|POSTROUTING' queue_list="" prepend_chain="" show_chain_heading=false one_go=false uniquify=true_print_usage() { cat <<- EOF Usage: $0 [-npofh] <starting-chain> -n shows chain's creation command as heading, useful for spotting empty chains -p prepends chain's name to each rule -o read everything in one go, 10x quicker when many small chains -f expand all references to a same chain, but beware of chain loops or chains referenced hundreds of times -h shows this help EOF }_expand_chain() { local chain_to_expand="${1}" local rules="" # if one_go selected, work with in-memory cache of chains if $one_go ; then rules="${all_chains[${chain_to_expand}]}" # otherwise read in chain to consider else rules="$(iptables -S "${chain_to_expand}")" fi $show_chain_heading && \ ! [[ "${chain_to_expand}" =~ ${builtin_chains_as_regexp} ]] && \ echo "-N ${chain_to_expand}" while read -r cmd chain rule ; do case "${cmd}" in -A) set -- ${rule} # look for target option in rule while [ -n "${1}" ] && ! [[ "${1}" =~ -(j|g) ]] ; do shift ; done # a few sanity checks [ -n "${1}" ] || continue # a rule with no target, skip it shift [ -n "${1}" ] || { echo "what!? empty target in ${rule}" >&2 ; continue ; } if [ -n "${all_chains[${1}]}" ] ; then # if target is a chain # add to queued chains if uniquify *not* requested or if chain never queued if ! $uniquify || [ -z "${queued_chains[${1}]}" ] ; then queue_list+="${1} " queued_chains[${1}]="1" fi fi # show rule echo "${prepend_chain:+[${chain_to_expand}] }${cmd} ${chain} ${rule}" ;; esac done <<<"${rules}" }### # ACTUAL EXECUTION STARTS HERE ## parse command options if any while getopts nphfo option ; do case $option in n) show_chain_heading=true ;; p) prepend_chain="1" ;; h) _print_usage ; exit 0 ;; o) one_go=true ;; f) uniquify=false ;; '?') exit 1 ;; esac done[ -n "${!OPTIND}" ] || { _print_usage ; exit 1 ; }# preparation step: # if one_go selected, slurp everything in if $one_go ; then # invoke explicit command only when stdin is the terminal [ -t 0 ] && exec 0< <(iptables -S) while read -r cmd chain rule ; do case "${cmd}" in -N) all_chains[${chain}]=" " # <<-- whitespace to make provision for empty chains ;; -A) # assign rule to its chain in cache all_chains[${chain}]+=$'\n'"${cmd} ${chain} ${rule}" ;; esac done # otherwise read in chain names only else while IFS= read -r chain ; do all_chains[${chain}]="1" done < <(iptables -S | sed -ne '/^-N /s///p') fi# expand starting chain _expand_chain ${!OPTIND}# breadth-first expand queued chains # as long as queue is not empty while [ "${#queue_list}" -gt 0 ] ; do # take next queued chain subchain="${queue_list%% *}" # expand it _expand_chain "${subchain}" # remove expanded chain from queue queue_list="${queue_list#${subchain} }" # queue gets updated by _expand_chain as needed doneexit 0Not very commented admittedly, but it shouldn’t be that tough to follow if you are familiar with Bash. If you run it with no options it will show a help summary. Note particularly that by default it expands each chain only once, even for chains that are referenced multiple times. You can request for a truly all-flattened output with -f option. I made it like that because I had a couple of chains referenced by thousands of other chains, and flattening all that would have taken hours (this script does not do parallel processing, of course). So keep that in mind if you have similar setups.
I'm looking for a program that takes the output of iptables -S and converts it to a breadth-first listing. Why? I'm doing some work on a router using VyOS where several layers of tables are pre-installed, so it is difficult to trace back all the rules connect to INPUT, FORWARD, and OUTPUT.As per @JeffSchaller 's [request], here is sample output that needs to be parsed: $ sudo iptables -S -P INPUT ACCEPT -P FORWARD ACCEPT -P OUTPUT ACCEPT -N LAN1_IN -N MINIUPNPD -N UBNT_FW_IN_SUSPEND_HOOK -N UBNT_PFOR_FW_HOOK -N UBNT_PFOR_FW_RULES -N UBNT_VPN_IPSEC_FW_HOOK -N UBNT_VPN_IPSEC_FW_IN_HOOK -N VYATTA_FW_IN_HOOK -N VYATTA_FW_LOCAL_HOOK -N VYATTA_FW_OUT_HOOK -N VYATTA_POST_FW_FWD_HOOK -N VYATTA_POST_FW_IN_HOOK -N VYATTA_POST_FW_OUT_HOOK -N WAN_IN -N WAN_LOCAL -N WAN_OUT -A INPUT -j UBNT_VPN_IPSEC_FW_HOOK -A INPUT -j VYATTA_FW_LOCAL_HOOK -A INPUT -j VYATTA_POST_FW_IN_HOOK -A FORWARD -j MINIUPNPD -A FORWARD -j UBNT_VPN_IPSEC_FW_IN_HOOK -A FORWARD -j UBNT_PFOR_FW_HOOK -A FORWARD -j UBNT_FW_IN_SUSPEND_HOOK -A FORWARD -j VYATTA_FW_IN_HOOK -A FORWARD -j VYATTA_FW_OUT_HOOK -A FORWARD -j VYATTA_POST_FW_FWD_HOOK -A OUTPUT -j VYATTA_POST_FW_OUT_HOOK -A LAN1_IN -m comment --comment LAN1_IN-10 -m state --state INVALID -j LOG --log-prefix "[LAN1_IN-10-D]" -A LAN1_IN -m comment --comment LAN1_IN-10 -m state --state INVALID -j DROP -A LAN1_IN -p udp -m comment --comment LAN1_IN-20 -m udp --dport 53 -m set --match-set dnsaddr dst -j RETURN -A LAN1_IN -p udp -m comment --comment LAN1_IN-30 -m set --match-set dnsaddr src -m udp --dport 53 -j RETURN -A LAN1_IN -m comment --comment LAN1_IN-60 -m state --state NEW -j RETURN -A LAN1_IN -m comment --comment LAN1_IN-70 -m state --state RELATED -j RETURN -A LAN1_IN -m comment --comment LAN1_IN-80 -m state --state ESTABLISHED -j RETURN -A LAN1_IN -m comment --comment "LAN1_IN-10000 default-action drop" -j LOG --log-prefix "[LAN1_IN-default-D]" -A LAN1_IN -m comment --comment "LAN1_IN-10000 default-action drop" -j DROP -A VYATTA_FW_IN_HOOK -i eth0 -j WAN_IN -A VYATTA_FW_IN_HOOK -i eth1 -j LAN1_IN -A VYATTA_FW_LOCAL_HOOK -i eth0 -j WAN_LOCAL -A VYATTA_FW_OUT_HOOK -o eth0 -j WAN_OUT -A VYATTA_POST_FW_FWD_HOOK -j ACCEPT -A VYATTA_POST_FW_IN_HOOK -j ACCEPT -A VYATTA_POST_FW_OUT_HOOK -j ACCEPT -A WAN_IN -m comment --comment WAN_IN-10 -m state --state ESTABLISHED -j RETURN -A WAN_IN -m comment --comment WAN_IN-20 -m state --state RELATED -j RETURN -A WAN_IN -m comment --comment WAN_IN-30 -m state --state INVALID -j LOG --log-prefix "[WAN_IN-30-D]" -A WAN_IN -m comment --comment WAN_IN-30 -m state --state INVALID -j DROP -A WAN_IN -m comment --comment "WAN_IN-10000 default-action drop" -j DROP -A WAN_LOCAL -m comment --comment WAN_LOCAL-10 -m state --state ESTABLISHED -j RETURN -A WAN_LOCAL -m comment --comment WAN_LOCAL-20 -m state --state RELATED -j RETURN -A WAN_LOCAL -m comment --comment WAN_LOCAL-30 -m state --state INVALID -j LOG --log-prefix "[WAN_LOCAL-30-D]" -A WAN_LOCAL -m comment --comment WAN_LOCAL-30 -m state --state INVALID -j DROP -A WAN_LOCAL -m comment --comment "WAN_LOCAL-10000 default-action drop" -j LOG --log-prefix "[WAN_LOCAL-default-D]" -A WAN_LOCAL -m comment --comment "WAN_LOCAL-10000 default-action drop" -j DROP -A WAN_OUT -m comment --comment WAN_OUT-10 -m state --state NEW -j RETURN -A WAN_OUT -m comment --comment WAN_OUT-20 -m state --state RELATED -j RETURN -A WAN_OUT -m comment --comment WAN_OUT-30 -m state --state ESTABLISHED -j RETURN -A WAN_OUT -m comment --comment WAN_OUT-40 -m state --state INVALID -j LOG --log-prefix "[WAN_OUT-40-D]" -A WAN_OUT -m comment --comment WAN_OUT-40 -m state --state INVALID -j DROP -A WAN_OUT -m comment --comment "WAN_OUT-10000 default-action drop" -j LOG --log-prefix "[WAN_OUT-default-D]" -A WAN_OUT -m comment --comment "WAN_OUT-10000 default-action drop" -j DROPI am selecting @LL3 's answer as correct, first past the post. @LL3 's answer has since been modified to be able to read stdin so I remove the patch doing same <patch removed>Kudos to perl-master @JeffSchaller 's (slightly later) complete answer showing both a breadth-first listing and separately a graphviz output.
How to convert `iptables -S` output to a breadth-first listing
Depending on how fancy you want to get, tree already can output directly to HTML format with the -H option (there are other options that affect the HTML output as well): tree -H /path/to/directory /path/to/directoryYou need to specify the path twice, because -H requires a root (it was designed around creating FTP directory pages.) You can change the default fonts being used by modifying the CSS that is output. If you just want to globally modify the font used, you can get sed to do the job with a slightly hacky regex: tree -H /path/to/directory /path/to/directory|sed "s/font-family : .*;/font-family : sans-serif;/"(Disclaimer: this is subject to breakage if tree changes the boilerplate.) If you need a PDF file from this, feel free to use your PDF converter of choice.
I am trying to visually show the tree structure of a directory. I know about the tree command and that works for me, but is there a program that takes the tree command output and makes it a bit more visually appealing? I understand that I could do this manually, but I was just wondering if there was software out that that would do this for me. Thanks
Make a visually better looking tree [closed]
The short answer using tree would be tree -PF *.datYou can also use (As I explained in my comment ) the GNUfind command. find . -type f -name '*.dat' -printf '|__ %P\n'You don't need GNUfind though. You can also use the following which is posix. find . -type f -name '*.dat' -print
I run with tree 1.7.0 tree -PF dat It gives . β”œβ”€β”€ 0deg/ β”œβ”€β”€ 105deg/ β”œβ”€β”€ 120deg/ β”œβ”€β”€ 135deg/ β”œβ”€β”€ 150deg/ β”œβ”€β”€ 15deg/ β”œβ”€β”€ 165deg/ β”œβ”€β”€ 180deg/ β”œβ”€β”€ 210deg/ β”œβ”€β”€ 240deg/ β”œβ”€β”€ 270deg/ β”œβ”€β”€ 300deg/ β”œβ”€β”€ 30deg/ β”œβ”€β”€ 330deg/ β”œβ”€β”€ 360deg/ β”œβ”€β”€ 45deg/ β”œβ”€β”€ 60deg/ β”œβ”€β”€ 75deg/ └── 90deg/where each folder contains a file [directory-name].dat. I would like have an output like . β”œβ”€β”€ 0deg/0deg.dat β”œβ”€β”€ 105deg/105deg.dat ...I run the command tree -Pf datand I get . β”œβ”€β”€ ./0deg β”œβ”€β”€ ./105deg β”œβ”€β”€ ./120deg β”œβ”€β”€ ./135deg β”œβ”€β”€ ./150deg β”œβ”€β”€ ./15deg β”œβ”€β”€ ./165deg β”œβ”€β”€ ./180deg β”œβ”€β”€ ./210deg β”œβ”€β”€ ./240deg β”œβ”€β”€ ./270deg β”œβ”€β”€ ./300deg β”œβ”€β”€ ./30deg β”œβ”€β”€ ./330deg β”œβ”€β”€ ./360deg β”œβ”€β”€ ./45deg β”œβ”€β”€ ./60deg β”œβ”€β”€ ./75deg └── ./90degI run the command tree -Pf *.datand I get . β”œβ”€β”€ ./0deg β”œβ”€β”€ ./105deg β”œβ”€β”€ ./120deg β”œβ”€β”€ ./135deg β”œβ”€β”€ ./150deg β”œβ”€β”€ ./15deg β”œβ”€β”€ ./165deg β”œβ”€β”€ ./180deg β”œβ”€β”€ ./210deg β”œβ”€β”€ ./240deg β”œβ”€β”€ ./270deg β”œβ”€β”€ ./300deg β”œβ”€β”€ ./30deg β”œβ”€β”€ ./330deg β”œβ”€β”€ ./360deg β”œβ”€β”€ ./45deg β”œβ”€β”€ ./60deg β”œβ”€β”€ ./75deg β”œβ”€β”€ ./90deg └── ./rem_angle.datHow can you get such an output?
Tree with directory name and filenames
I think, you should revert the order of du -h with tac and then put some formatting with sed. This one should work for "normal" directory names (without control characters): du -h | tac | sed 's_[^/[:cntrl:]]*/_--_g;s/-/|/'Or use find -exec: find . -type d -exec du -sm {} \; | sed 's_[^/[:cntrl:]]*/_--_g;s/-/|/'
is there a nice way to combine: ls -R | grep "^[.]/" | sed -e "s/:$//" -e "s/[^\/]*\//--/g" -e "s/^/ |/"(displays directory as tree) with du -h ... (for each listed dir)Without installing any extra package, like tree, dutree ?
du + tree command (without tree installation)
Should be pretty portable: find . -type f | sortOn the off chance that your input data contains files with new lines in their name, I believe this should handle them better (thanks to Kusalananda for pointing out this possible scenario): find . -type f -print0 | sort -z | tr '\0' '\n'
How to list files recursively, in alphabetical order and without lines that show exclusively folder names? For example, I can get the following output with tree --dirsfirst -fihan * -o filelist: 00.-ScriptHookV [1.0.1737.0] [128K] 00.-ScriptHookV [1.0.1737.0]/dinput8.dll* [1.2M] 00.-ScriptHookV [1.0.1737.0]/ScriptHookV.dll* 01.-ScriptHookVDotNet [2.10.10] [ 891] 01.-ScriptHookVDotNet [2.10.10]/LICENSE.txt* [1.8K] 01.-ScriptHookVDotNet [2.10.10]/README.txt* [1018K] 01.-ScriptHookVDotNet [2.10.10]/ScriptHookVDotNet2.dll* [7.5K] 01.-ScriptHookVDotNet [2.10.10]/ScriptHookVDotNet2.pdb* [ 92K] 01.-ScriptHookVDotNet [2.10.10]/ScriptHookVDotNet2.xml* [ 34K] 01.-ScriptHookVDotNet [2.10.10]/ScriptHookVDotNet.asi* 02.-Heap Limit Adjuster [1.0.0] [ 98K] 02.-Heap Limit Adjuster [1.0.0]/GTAV.HeapAdjuster.asi* 03.-OpenIV [3.1] [132K] 03.-OpenIV [3.1]/OpenIV.asi* 04.-Enhanced Native Trainer [1.41 Update 1] [ 15M] 04.-Enhanced Native Trainer [1.41 Update 1]/EnhancedNativeTrainer.asi* [8.4K] 04.-Enhanced Native Trainer [1.41 Update 1]/ent-config.xml*But I need this kind of output (not necessarily with filesizes): [128K] 00.-ScriptHookV [1.0.1737.0]/dinput8.dll [1.2M] 00.-ScriptHookV [1.0.1737.0]/ScriptHookV.dll [ 891] 01.-ScriptHookVDotNet [2.10.10]/LICENSE.txt [1.8K] 01.-ScriptHookVDotNet [2.10.10]/README.txt [1018K] 01.-ScriptHookVDotNet [2.10.10]/ScriptHookVDotNet2.dll [7.5K] 01.-ScriptHookVDotNet [2.10.10]/ScriptHookVDotNet2.pdb [ 92K] 01.-ScriptHookVDotNet [2.10.10]/ScriptHookVDotNet2.xml [ 34K] 01.-ScriptHookVDotNet [2.10.10]/ScriptHookVDotNet.asi [ 98K] 02.-Heap Limit Adjuster [1.0.0]/GTAV.HeapAdjuster.asi [132K] 03.-OpenIV [3.1]/OpenIV.asi [ 15M] 04.-Enhanced Native Trainer [1.41 Update 1]/EnhancedNativeTrainer.asi [8.4K] 04.-Enhanced Native Trainer [1.41 Update 1]/ent-config.xmlAny suggestions?
List files recursively, in alphabetical order and without lines that show exclusively folder names
When you use an unquoted globbing pattern on the command line, the shell will try to match it against filenames. If no filename matches the pattern, most shells will keep the unexpanded pattern (zsh would by default complain, as would bash with set -u). You obviously have some file whose name matches *sta*, but not fsta* or *stab. The shell expands *sta* to the name of that file, which means that the pattern no longer matches fstab under /etc. The solution is to use single or double quotes around the pattern (and let tree do its own pattern matching internally).
Why the last tree is not finding fstab? tree /etc -P fstab --prune /etc └── fstab 0 directories, 1 file. tree /etc -P fsta* --prune /etc └── fstab 0 directories, 1 file . tree /etc -P *stab --prune /etc └── fstab 0 directories, 1 fileWhat is happening here? According to my understanding it should find at least fstab tree /etc -P *sta* --prune /etc 0 directories, 0 files
Confused about "tree" not finding a file
Use a wildcard: tree -I '*_old' -L 4Reference: man tree (my emphasis)-I pattern Do not list those files that match the wild-card pattern.
tree shows ... β”‚ β”œβ”€β”€ template_one_file.sh β”‚ β”œβ”€β”€ template_sed.sh β”‚ β”œβ”€β”€ testy.sh β”‚ β”œβ”€β”€ tmp β”‚ β”‚ β”œβ”€β”€ file1.html.13567_old β”‚ β”‚ β”œβ”€β”€ file2.html.13567_old β”‚ β”‚ β”œβ”€β”€ file3.html.13567_old β”‚ β”‚ └── file4.html.13567_old β”‚ └── use_case_to_add_etc_2_numbers └── vi β”œβ”€β”€ vim_tips_and_chearsheet └── vi_stuff160 directories, 713 filesand I can ignore the tmp directory (for example) with tree -I 'tmp' -L 4 ... β”‚ β”œβ”€β”€ template_multiple_files.sh β”‚ β”œβ”€β”€ template_one_file.sh β”‚ β”œβ”€β”€ template_sed.sh β”‚ β”œβ”€β”€ testy.sh β”‚ └── use_case_to_add_etc_2_numbers └── vi β”œβ”€β”€ vim_tips_and_chearsheet └── vi_stuff157 directories, 709 filesbut why can I not ignore individual files such as the _old files with tree -I 'old' -L 4which still shows the _old files ... β”‚ β”œβ”€β”€ template_multiple_files.sh β”‚ β”œβ”€β”€ template_one_file.sh β”‚ β”œβ”€β”€ template_sed.sh β”‚ β”œβ”€β”€ testy.sh β”‚ β”œβ”€β”€ tmp β”‚ β”‚ β”œβ”€β”€ file1.html.13567_old β”‚ β”‚ β”œβ”€β”€ file2.html.13567_old β”‚ β”‚ β”œβ”€β”€ file3.html.13567_old β”‚ β”‚ └── file4.html.13567_old β”‚ └── use_case_to_add_etc_2_numbers └── vi β”œβ”€β”€ vim_tips_and_chearsheet └── vi_stuff160 directories, 713 filesI tried '.*old' and '.*old$' patterns but that didn't help.
Why does 'tree' command ignore directories but not files
To enable universe, run sudo add-apt-repository universeThen update the indexes: sudo apt updateYou’ll be able to install the tree package once that’s done: sudo apt install tree
I tried to use the tree command in a bootable USB Ubuntu environment but it showed that it is not installed so I tried sudo apt install tree, but it didn't work and reported that it was unable to locate package and also said to enable component universe. I don't know what component universe is. How can I fix this?
Tree command package installation?
Here I found the problem. The correct way to insert dates is using dots, e.g., 2012.03.10 and not slashes. The problem was the use of Gnumeric to edit the CSV file.
I'm using gnuclad to create a tree. The problem is that I'm not able to change the starting date. I'm using the data below, from the default example. #,Nodes,,,,,,,,,,,,, #,Name,Color,Parent,Start,Stop,Icon,Description,[Namechange,When,Description,[Namechange,When,Description,". . . ]]" N,Name here,#f00,,2002/12/01,2007/08/20,,,,,,,,,As you can see on the image, the node starts always at January.Also, is it possible to turn off the title box without editing the conf file? The config file example.conf is the default one: # gnuclad example config file # gnuclad has more than 50 configuration options, of # which only a few are listed here. # For a detailed explanation, consult the included manual. # You can always generate a full configuration file by # specifying CONF as gnuclad's output.# If you comment or delete an option, # gnuclad will use the built-in defaults. # Allowed syntax is: # option=value # option = value # option= 'value' # option ="value" # option = three word value # option = "three word value" # ...infoBoxTitle = Title infoBoxText = Lorem ipsum dolor sit amet, infoBoxText = consectetuer adipiscing elit infoBoxX = 10 infoBoxY = 45 infoBoxWidth = 166 infoBoxHeight = 60# use ascii string width heuristics asciiStrings = 1# orientation goes from 0 to 3 orientation = 0#treemode goes from 0 to 2 treeMode = 0mainBackground = #fff rulerWidth = 2 rulerColor = #ddd rulerMonthWidth = 1 rulerMonthColor = #eaeaealineWidth = 4 offsetPX = 20 yearPX = 100labelFontColor = #000 labelBGOpacity = 50#nameChangeType can be 0 or 1 nameChangeType = 0#derivType can be 0 or 1 derivType = 0 dotRadius = 10 smallDotRadius = 5descriptionType = 1
gnuclad does not change starting date
You could try something like: sed -n "/\[fencedtitle\]/{:a;N;/----/!ba;N;s/.*\n/$(tree)\n/};p" fileBut this will be problematic if the output of tree contains characters that are special for regex. If you save the output of tree to a file: tree > my-outThen you can read it in sed without too many problems: sed -n '/\[fencetitle\]/{p;n;p;r my-out :a;n;/^----$/!ba};p' file(Yes, the r command does require a new line after it, no commands may follow it on the same line.) The p;n;p; just prints the start of the fence, then we read the file, then we skip everything till the end of the fence. You can end the line after the r command by splitting out the rest into a separate sed expression: sed -ne '/\[fencetitle\]/{p;n;p;r my-out' -e ':a;n;/^----$/!ba};p' file
I'm attempting to replace a "fenced" block of text with the output from the tree command in linux (specifically in a make file). Here's my input file: some text... [fencetitle] ---- . β”œβ”€β”€ file1.txt └── test └── file2.txt1 directory, 2 files ---- some more text...And I'd like to replace the contents with output from the tree command: some text... [fencetitle] ---- . β”œβ”€β”€ file1.txt β”œβ”€β”€ newfile.txt └── test └── file2.txt1 directory, 3 files ---- some more text...Using the sed command, I can't seem to match using newlines with the line [fencedtitle] and ---- to ----. I am able to replace text between [fencedtitle] and ---- with the following command, however: sed -n '/\[fencedtitle\]/{:a;N;/----/!ba;N;s/.*\n/REPLACEMENT\n/};p' fileBut I can't seem to then replace REPLACEMENT with the output from the tree command. Is sed the right approach here, or is something else more appropriate?
Replace fenced block with output of command in bash
The tree utility has a specific option, -P, for specifying a pattern that the filenames must match to be part of the output. The type of pattern used with -P is a shell filename globbing pattern, and as such, it needs to be quoted to avoid having the shell expand it on the command line. tree -P 'hw*' .Since your current directory doesn't contain any name matching *hw (and since you are using a shell that does not complain about non-matching globbing patterns, like zsh would do by default, and like bash would do with its failglob shell option set), the pattern wasn't expanded when you tried to use it. However, that pattern only matches names that end in the string hw. I can however not explain why you get that output when using hw* on the command line. Example: $ tree . . β”œβ”€β”€ exp β”‚ β”œβ”€β”€ hi β”‚ └── hw β”œβ”€β”€ src β”‚ β”œβ”€β”€ hi.cpp2 β”‚ └── hw.cpp2 β”œβ”€β”€ ssbuild.bash β”œβ”€β”€ sslogin.bash └── tmp β”œβ”€β”€ hi.cpp └── hw.cpp3 directories, 8 files$ tree -P 'hw*' . . β”œβ”€β”€ exp β”‚ └── hw β”œβ”€β”€ src β”‚ └── hw.cpp2 └── tmp └── hw.cpp3 directories, 3 files
I would like tree to display the hw files in the sub-directories like this: . β”œβ”€β”€ exp β”‚ └── hw β”œβ”€β”€ src β”‚ └── hw.cpp2 └── tmp └── hw.cpp$ /usr/bin/tree --noreport . displays all of the files: . β”œβ”€β”€ exp β”‚ β”œβ”€β”€ hi β”‚ └── hw β”œβ”€β”€ src β”‚ β”œβ”€β”€ hi.cpp2 β”‚ └── hw.cpp2 β”œβ”€β”€ ssbuild.bash β”œβ”€β”€ sslogin.bash └── tmp β”œβ”€β”€ hi.cpp └── hw.cpp/usr/bin/tree --noreport -P *hw . gets hw w/o an extension: . β”œβ”€β”€ exp β”‚ └── hw β”œβ”€β”€ src └── tmp/usr/bin/tree --noreport -P hw* . produces: . β”œβ”€β”€ exp β”œβ”€β”€ src └── tmpVersion info /usr/bin/tree --version: tree v2.1.0 Β© 1996 - 2022 by Steve Baker, Thomas Moore, Francesc Rocher, Florian Sesser, Kyosuke Tokoro
Tree display hw, hw.cpp & hw.cpp2 in sub-directories
tail is a standard filter to print last line(s). To print one last line use tail -n 1. tree -a | tail -n 1
I want to keep only the last line of tree's output or the file+directory count report. Preferably, with the -a switch. An example output I desire: 585 directories, 37722 filesIs this possible with tree?
tree command to only output file and directory count?
If you want to check the number of .py files in your tree to compare it to the number found by cloc, I’d suggest something like find . -type f -name \*.py -printf '1' | wc -cinstead.
I learnt that there was a command cloc to count lines of code. Now I wonder if it the file types are accurate? Should I look a the cloc project to know how file types are detected? The reason I wonder is that cloc seems to have false positives if I'm not mistaken when I compare the file types to the tree|ls *.py there is no output even though cloc reports python files in the current directory.
Statistics for project filestypes [closed]
You have read, but not execute/search permissions to the containing directory. Easy to reproduce with: mkdir -p foo/bar; chmod -x foo; ls -l foo ls: cannot access 'foo/bar': Permission denied total 0 d????????? ? ? ? ? ? barOn Linux and BSD, ls is able to get that it's a directory from the d_type field of the directory entry, but not much more. That may also happen in other situations where ls is not able to access the actual inode, but only the directory entry which points to it (as when the file or directory inode has disappeared before ls was able to stat() it -- see this, or when the it's an inaccessible mount point -- see this).
What is the situation why ls -l returns a list of subdirectories in the form below? d????????? ? ? ? ? ? SubdirectoryA tree launched on that directory returns 0 directories, 0 files for example. The system seems to know the name of the subdirectory but cannot find it. Which missing link confuses ls? Late note. On directories, thus not on files, see also:Linux local directory permissions as question-marks for non-root
What does the output `d?????????` in `ls -l` mean? [duplicate]
In zsh: for d (parent-dir/*/*(N/)) (cd -- $d && tree) > output-dir/$d:t.txt
Is it possible to use tree to create several output files without being cd ~/ into the directory I want to create a tree file? For example, I have a directory called parent-dir. Inside of parent-dir are subdirectories titled a, b, c to z and one also titled 0-9. Inside of those subdirectories are more subdirectories that are titled at random using lower/upper case, numbers and some special characters. (It is at this level I want to create a tree .txt output file)Here is the directory structure: parent-dir ( <-- I will be cd ~/ here and run cmd from here) |_a | |_ahgfVFCJC6.h78 ( <-- cmd should create a tree titled ahgfVFCJC6.h78.txt) | | |_file.jpg | | |_file.mp4 | | | |_a34grBVFHEwerv ( <-- cmd should create a tree titled a34grBVFHEwerv.txt) | |_file.txt | |_file.mp3 | |_b | |_bhlHKH.7tbh ( <-- cmd should create a tree titled bhlHKH.7tbh.txt) | |_file.png | |_file.txt...and so on... The .txt files created using `tree`:ahgfVFCJC6.h78.txt a34grBVFHEwerv.txt bhlHKH.7tbh.txtshould be outputted in a specified directory (example: ~/Desktop/Tree)I am hoping to run a command while in parent-dir because in a alone there are thousands of directories like ahgfVFCJC6.h78 (but named differently). Having to cd into each of those sub-subdirectories would take far too much time.
Using 'TREE' for sub-subdirectories
Even if the tree tool doesn't support sorting by size directly, you can still do it using tree and sort. You can use the following command to list all the files and their paths in the given folder and subfolders with their file size and then use the sort tool to sort them by the second column of tree output (that is these sizes, being the first column all the [ symbols). We use grep here to filter just files with a given extension. Here's the command: tree -sifF /opt/aplicaciones/gio/ | grep -v '/$' | grep ".jar" | sort -k2 -rnHere's a sample output with a somewhat large quantity of files so you can see how it behaves: [ 89702805] /myapp/first_folder/artifact/this-is-a-file-number-1.jar [ 89511250] /myapp/first_folder/artifact/this-is-a-file-number-2_22_11_2022.jar [ 89508457] /myapp/first_folder/artifact/this-is-a-file-number-2.jar [ 89487284] /myapp/first_folder/artifact/this-is-a-file-number-2_backup.jar [ 73631126] /myapp/first_folder/artifact/this-is-a-file-number-3.jar [ 73416714] /myapp/first_folder/artifact/this-is-a-file-number-4.jar [ 72904056] /myapp/second_folder/artifact/this-is-a-file-number-5.jar [ 72870839] /myapp/second_folder/artifact/this-is-a-file-number-6.jar [ 72824807] /myapp/second_folder/artifact/this-is-a-file-number-7.jar [ 72822778] /myapp/second_folder/artifact/this-is-a-file-number-8.jar [ 72822392] /myapp/second_folder/artifact/this-is-a-file-number-9.jar [ 72822125] /myapp/second_folder/artifact/this-is-a-file-number-10.jar [ 72821288] /myapp/second_folder/artifact/this-is-a-file-number-11.jar [ 72808348] /myapp/first_folder/artifact/this-is-a-file-number-12.jar [ 72794504] /myapp/second_folder/artifact/this-is-a-file-number-13.jar [ 70309496] /myapp/first_folder/artifact/this-is-a-file-number-14.jar [ 70298847] /myapp/first_folder/artifact/this-is-a-file-number-15.jar [ 70286111] /myapp/first_folder/artifact/this-is-a-file-number-16.jar [ 70283872] /myapp/first_folder/artifact/this-is-a-file-number-17.jar [ 70281102] /myapp/first_folder/artifact/this-is-a-file-number-18.jar [ 70275702] /myapp/first_folder/artifact/this-is-a-file-number-19.jar [ 70274483] /myapp/first_folder/artifact/this-is-a-file-number-20.jar [ 70273588] /myapp/first_folder/artifact/this-is-a-file-number-21.jar [ 70273058] /myapp/first_folder/artifact/this-is-a-file-number-22.jar [ 70271031] /myapp/first_folder/artifact/this-is-a-file-number-23.jar [ 70265460] /myapp/first_folder/artifact/this-is-a-file-number-24.jar [ 70090818] /myapp/first_folder/artifact/this-is-a-file-number-25.jar [ 69510384] /myapp/first_folder/artifact/this-is-a-file-number-26.jar [ 68674140] /myapp/first_folder/artifact/this-is-a-file-number-27.jar [ 68367619] /myapp/second_folder/artifact/this-is-a-file-number-28.jar [ 65897101] /myapp/first_folder/artifact/this-is-a-file-number-29.jar [ 65011678] /myapp/first_folder/artifact/this-is-a-file-number-30.jar [ 65010373] /myapp/second_folder/artifact/this-is-a-file-number-31.jar [ 51954261] /myapp/second_folder/artifact/this-is-a-file-number-32__test.jar [ 48092911] /myapp/second_folder/artifact/this-is-a-file-number-32.jar [ 43081254] /myapp/second_folder/artifact/this-is-a-file-number-33.jar [ 23357588] /myapp/third_folder/artifact/this-is-a-file-number-34.jarA [ 23357588] /myapp/third_folder/artifact/this-is-a-file-number-34.jarNow, the explanation of the used options: From the man, about tree:-s Print the size of each file in bytes along with the name. -i Makes tree not print the indentation lines, useful when used in conjunction with the -f option. -f Prints the full path prefix for each file. -F Append a '/' for directories, a '=' for socket files, a '*' for executable files and a '|' for FIFO's, as per ls -FAbout sort:-k --key=POS1[,POS2] Start a key at POS1 (origin 1), end it at POS2 (default end of line) i.e. Just think about it as columns separated by whitespaces. -r --reverse Reverse the result of comparisons -n --numeric-sort Compare according to string numerical value
Which option should be used with tree command line tool to get sort from biggest to smallest? β”œβ”€β”€ [4.0K] types2 β”‚ └── [ 116] types2.go β”œβ”€β”€ [4.0K] types3 β”‚ β”œβ”€β”€ [ 689] types3.go β”‚ └── [ 0] types3.go~ β”œβ”€β”€ [4.0K] web β”‚ β”œβ”€β”€ [ 149] index.html β”‚ β”œβ”€β”€ [ 647] web.go β”‚ └── [ 0] web.go~ β”œβ”€β”€ [4.0K] wordcount β”‚ β”œβ”€β”€ [ 996] wordcount.go β”‚ └── [ 773] wordcount.go~ └── [4.0K] zero β”œβ”€β”€ [ 97] zero.go └── [5.8K] zero.o
How to sort from smallest to biggest with `tree` command line tool?
This is a known bug. Apparently it was fixed yesterday, 2023-05-31. I'm not seeing where in https://gitlab.com/OldManProgrammer/unix-tree/-/commit/84fa3ddff51b30835a0f9c4a9e4c9225970f9aff it was fixed, but this is between you and Steve Baker.
I gave the command tree -J to my machine, and this is a portion of the output it gave: { "type": "file", "name": "ca-certificates.conf" }, { "type": "file", "name": "ca-certificates.conf.dpkg-old" }, { "type": "directory", "name": "chatscripts" } { "error": "error opening dir" }, { "type": "directory", "name": "chromium", "contents": [{ "type": "directory", "name": "native-messaging-hosts" }] }Have a look at that "error" node: it does not appear to be valid Json (a , is missing). How can I avoid the displaying of such errors? Using v2.0.2
Command "tree -J" returns invalid Json
This is written in a confusing manner and I'm assuming comes from a basic linux/unix test. I can explain. It will seem clearer if it is on multiple lines. The ; char means end of a command. The mkdir command can do multiple things with one execution. cd /You will be in / as your current working directory. mkdir a b c a/a b/aCreates directories relative to your cwd: /a, /b, /c, /a/a, /b/a cd aYour cwd becomes /a mkdir ../e ../a/f ../b/a/gCreates directories relative to current location. The .. means to go up one. Above your cwd of /a is / so you create /e, then /a/f, then /b/a/g dirs. cd ../b/./While .. means parent directory, . means this directory. So, from /a you would go up one (..) then into /b, then stay where you are (.). A trailing / after a directory name means only that it is a directory and is optional. mkdir /a/k a/b ../a/./b /cAgain this needs to be broken up since it is obviously written to be confusing. Creates /a/k, since the leading / means an absolute path, then /b/a/b since you are already in /b and it is relative (does not start with /). Next is /a/b since you are already in /b and the . does nothing. Then it will try to create /c but this already exists. I would suggest working through this yourself on a command line and see if it makes sense.
I need to draw the tree structure of the following code. cd /; mkdir a b c a/a b/a; cd a; mkdir ../e ../a/f ../b/a/g; cd../b/./; mkdir /a/k a/b ../a/./b /cI know that: cd /; (goes to root) , mkdir creates directories a b c but I can't understand the rest of the line. Any thoughts would be really helpful.
Tree structures and directories [closed]
Try this: tree | sed '/\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 image\.[0-9]\+\.jpg/d; s/\(\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 image\.\)[0-9]\+\(\.jpg\)/\1####\2/'The first /.../d; deletes all lines containing β”œβ”€β”€ image.[0-9]+.jpg (pseudo-pattern) entries The second s/.../\1####\2/ replaces the last line └── image.[0-9]+.jpgOutput: $ tree | sed '/\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 image\.[0-9]\+\.jpg/d; s/\(\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 ima ge\.\)[0-9]\+\(\.jpg\)/\1####\2/' . β”œβ”€β”€ directory1 β”‚ └── image_sequence β”‚ └── image.####.jpg └── directory2 β”œβ”€β”€ someanotherfile.ext └── somefile.ext3 directories, 8 filesThis will of course only work if all files in image_sequence match the image pattern and will modify filenames in other directories matching the patterns. If the last file in image_sequence for example is readme.txt, then you will remove all image entries instead.
I'm in a directory where running tree command produces something like this: β”œβ”€β”€ directory1 β”‚ └── image_sequence β”‚ β”œβ”€β”€ image.0001.jpg β”‚ β”œβ”€β”€ image.0002.jpg β”‚ β”œβ”€β”€ image.0003.jpg β”‚ β”œβ”€β”€ image.0004.jpg β”‚ β”œβ”€β”€ image.0005.jpg β”‚ └── image.0006.jpg β”‚ └── directory2 β”œβ”€β”€ somefile.ext └── someanotherfile.ext2The image sequence inside image_sequence produces a large listing that I want to trim. My desired output is something like below: β”œβ”€β”€ directory1 β”‚ └── image_sequence β”‚ └── image.####.jpg β”‚ └── directory2 β”œβ”€β”€ somefile.ext └── someanotherfile.ext2Can the output of tree command somehow be modified?
How to shorten image sequence output in tree command?
echo "alias tree='tree -C'" >>/etc/profile.d/tree-C.sh Then logout and log back in. Putting it in /etc/profile.d makes this shortcut available to all users on the machine so that it'll work even if you change user accounts (su/sudo)
I am tired of using the -C with the tree all the time. I would like to tweak the tree to colorize files and directories to its automatic behavior so that I don't have to type the -C flag all the time. How to enable automatically colorize the output of tree without using -C flag in bash all the time?
How to enable automatically colorize the output of tree without using -C flag in bash all the time?
You can use find with the -L option, e.g., find -L . -type f -exec grep foo {} \;That makes find follow symbolic links. Quoting POSIX:-L Cause the file information and file type evaluated for each symbolic link encountered as a path operand on the command line or encountered during the traversal of a file hierarchy to be those of the file referenced by the link, and not the link itself. If the referenced file does not exist, the file information and type shall be for the link itself.
I have a folder with symlinks which are pointing to other folders, how can i recursively look into those folders? I would like to do a grep on those results to search for matches. doing tree will only list the symlink as files.
Tree/Find command on symlinks
Narrowing Down of Errors I see lots of things that need attention before we worry about grub26 packages (at least) need removed. 174 packages need upgraded. Grub needs a bit of investigation and a possible fix as oldfred's comment suggests.We need to knock out the small steps (1 and 2) to keep from possibly having to fix grub twice. These types of answers are what I like doing for 2 reasons:I can help new Linux users understand that rebooting in Linux is way different than rebooting in Windows. As a new Linux user, I hope that the OP will pass his knowledge on, like I am doing here.Small Things First Just from looking at the output snippet, I know that the package manager is APT, short for the Advanced Packaging Tool. In case you need it, try mam apt.apt update && apt autoremove - Should remove the 26 in 1 above. apt upgrade - Should Download and install 174 packages noted in 2(which may include grub). This may take awhile depending on your internet connection.Note: The upgrade may abort at the same error the OP pasted in his question. I would expect that, but we want the 174 package set to upgrade as many as is possible. If the upgrade aborts, continue with the Elephant and repeat step 2 afterwards And Now the Elephant in the Room Oldfred, well he's old, but he is right: grub-install: warning: File system `ext2' doesn't support embedding. grub-install: warning: Embedding is not possible. GRUB can only be installed in this setup by using blocklists. However, blocklists are UNRELIABLE and their use is discouraged..Before we can reliably determine what type of grub install we need a few things in no particular order:Your BIOS/UEFI version: sudo dmidecode -s bios-version Is UEFI on/supported: sudo dmidecode -t 0 | grep UEFI Your CPU: cpuid | less Your Partition List and Table Type: sudo parted --listFor grub-efi-amd64 to work, you must have an ESP/EFI partition type of FAT32 and a 64 bit CPU. Bullet 3 can be googled etc. as follows: Is family X Model Y CPU 64-bit, where X and Y are the integer numbers in the Family and Model Rows. Bullet 4 must contain an output of EFI Partition, fstype: fat32, and a Table Type of gpt. Bullet 2 must contain "is supported" From the looks of the error quoted earlier, I'm assuming you attempted to embed the grub boot code into the root partition, which the installer formatted as ext2. If the OP used the entire disk for the install, grub needs to be reinstalled using the entire disk. This option will work whether EFI or not. If an EFI partition exists, grub needs to be reinstalled in it only. Please add the output of the above 4 bullets to your question, and I will update this answer with the appropriate command.Update Based on the updates the OP provided from dmidecode and parted I'm going to safely say that grub-pc is the proper grub architecture. Since the OP has chosen to only install WattOS on the machine, we can safely embed grub in the boot-sector for the entire HDD with: sudo grub-install /dev/sda && sudo update-grub sudo reboot After restarting, continue with: apt update && apt-upgrade If grub ever needs upgrading again, just issue the commands above with each upgrade(In about 15 years of various Linux distributions, I think I have upgraded grub less than 10 times. It isn't a very common package to upgrade in my opinion). Notes: By leaving off a partition number in the grub-install command, we've told grub it's acceptable to embed for the entire disk. If update-grub fails (Issue these in sequence):sudo grub-install /dev/sda sudo grub-mkconfig -o /boot/grub/grub.cfg sudo reboot
I just installed tree via sudo apt-get install treeand my terminal suddenly decided to update grub. Last week, I installed tree, and a similar thing happened. However, when I restarted my PC later that night it booted into a window displaying Grub _and didn't change. Eventually I reinstalled my OS (I'm on WattOS, and just installed it on a new PC last Tuseday, so it wasn't the end of the world - it just took 5 hours to set everything up again). Grub installed with a number of errors which I vaguely recall seeing last time (Included at the bottom of my post to make it easier to read). I've googled around for :Why does tree update grub? Why did grub upgrade/update?But I haven't had any luck. I suspect that I'm probably missing something. Can anyone explain:Why this happened Does this mean anythings wrong If I should/can do anything to fix it.I'd rather not reinstall everything (for obvious reasons!) Thanks. Errors encountered when installing tree: sudo apt-get install tree Reading package lists... Done Building dependency tree... Done Reading state information... Done The following packages were automatically installed and are no longer required: gimp-data libamd2 libbabl-0.1-0 libcamd2 libccolamd2 libcholmod3 libgegl-0.4-0 libgegl-common libgexiv2-2 libgimp2.0 libhpmud0 libimagequant0 libmetis5 libqt5designer5 libqt5help5 libqt5sql5 libqt5sql5-sqlite libqt5test5 libsane-hpaio libumfpack5 printer-driver-hpcups printer-driver-postscript-hp python3-dbus.mainloop.pyqt5 python3-notify2 python3- olefile python3-pexpect python3-pil python3-ptyprocess python3-pyqt5 python3-pyqt5.sip python3-renderpm python3-reportlab python3-reportlab- accel vlc-plugin-samba xsane xsane-common Use 'sudo apt autoremove' to remove them. The following NEW packages will be installed: tree 0 upgraded, 1 newly installed, 0 to remove and 174 not upgraded. 1 not fully installed or removed. Need to get 49.6 kB of archives. After this operation, 118 kB of additional disk space will be used. Get:1 http://deb.debian.org/debian bullseye/main amd64 tree amd64 1.8.0-1+b1 [49.6 kB] Fetched 49.6 kB in 0s (110 kB/s) Selecting previously unselected package tree. (Reading database ... 123032 files and directories currently installed.) Preparing to unpack .../tree_1.8.0-1+b1_amd64.deb ... Unpacking tree (1.8.0-1+b1) ... Setting up grub-pc (2.06-3~deb11u6) ... Installing for i386-pc platform. grub-install: warning: File system `ext2' doesn't support embedding. grub-install: warning: Embedding is not possible. GRUB can only be installed in this setup by using blocklists. However, blocklists are UNRELIABLE and their use is discouraged.. Installation finished. No error reported. Generating grub configuration file ... Found background: /usr/share/wattOS/splash.png Found background image: /usr/share/wattOS/splash.png Found linux image: /boot/vmlinuz-5.10.0-19-amd64 Found initrd image: /boot/initrd.img-5.10.0-19-amd64 Warning: os-prober will be executed to detect other bootable partitions. Its output will be used to detect bootable binaries on them and create new boot entries. Found Debian GNU/Linux 11 (bullseye) on /dev/mmcblk0p2 done Setting up tree (1.8.0-1+b1) ... Processing triggers for man-db (2.9.4-2) ...Update I rebooted by accident, and my PC hanged again. I then reinstalled WattOS as the only OS on my hardrive, and everything worked fine. I just saw @eyoung100 s answer, and I ran sudo apt upgradewhich ran with no errors. Then I ran sudo apt autoremovewhich half way through gave me the same screen as last time: The grub-pc package is being upgraded. This menu allows you to select which devices you'd like grub-install to be automatically run for, if any. Running grub-install automatically is recommended in most situations, to prevent the installed GRUB core image from getting out of sync with GRUB modules or grub.cfg. If you're unsure which drive is designated as boot drive by your BIOS, it is often a good idea to install GRUB to all of them. Note: it is possible to install GRUB to partition boot records as well, and some appropriate partitions are offered here. However, this forces GRUB to use the blocklist mechanism, which makes it less reliable, and therefore is not recommended.I haven't selected OK, as last time that gave me errors. When I then tried in another terminal sudo apt upgradeIt responded with Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 39623 (apt) Which is hardly suprising. I tried closing that shell with ctrl-c and ctrl-x, but neither helped. I could close the window, but I'm concerned to. More information asked forResult ofsudo dmidecode -s bios-versionis 8GET38WW (1.15 )Result ofsudo dmidecode -t 0 | grep UEFIis nothing. (I guess that means that it's not supported).Result ofcpuid | lessis bash: cpuid: command not foundAll I can say is it's a Lenovo Thinkpad L520, it's refurbished, and I haven't changed the CPU. (I don't know about the previous owner).Result ofsudo parted --listis Model: ATA ADATA SU630 (scsi) Disk /dev/sda: 240GB Sector size (logical/physical): 512B/512B Partition Table: msdos Disk Flags: Number Start End Size Type File system Flags 1 1049kB 231GB 231GB primary ext4 boot 2 231GB 240GB 9449MB primary linux-swap(v1)I can't see anything about fstype or gpt. As I said, I attempted to install it onto a wiped disk. Thank you for your time!
Installing tree installed grub - is it something to worry about?
The tree utility on Linux has a -f option that lists each directory entry with its relative pathname: $ tree -f ufw ufw β”œβ”€β”€ ufw/after6.rules β”œβ”€β”€ ufw/after.init β”œβ”€β”€ ufw/after.rules β”œβ”€β”€ ufw/applications.d β”‚ β”œβ”€β”€ ufw/applications.d/cups β”‚ β”œβ”€β”€ ufw/applications.d/openssh-server β”‚ └── ufw/applications.d/postfix β”œβ”€β”€ ufw/before6.rules β”œβ”€β”€ ufw/before.init β”œβ”€β”€ ufw/before.rules β”œβ”€β”€ ufw/sysctl.conf β”œβ”€β”€ ufw/ufw.conf β”œβ”€β”€ ufw/user6.rules └── ufw/user.rules1 directory, 13 filesThis would allow you to always know the exact pathname for each entry, relative to the top-level directory.
When you generate a tree for a large directory base with innumerable sub-directories and associated files, with -a option, often you get a large file with thousands of lines. While traversing the tree depicted within this file, it often becomes difficult to keep track of which directory you are in at any given point in time, as you descend deeper into the tree. As you scroll down the file from within a text editor like vi, you can lose track of the outer level directory labels. So my question is, is there a way to overcome this issue? Is it possible at all to get some kind of perspective of the outer level directory labels, as you descend deeper into the tree?
tree: Is there a way to maintain visibility of outer level directory labels when scrolling?
You can use -ls in find to get the owner size, and modification time: find . -type f -size +10M -ls
I want to find user, size, modified date and full file path of all files in sub-directories starting from a dir. I have got to following so far: nohup sudo \ tree /work/mydir \ -sufiD \ --noreport \ --timefmt="%Y-%m-%d" | \ sed -e 's/ \+/ /g' -e 's/\[//g' -e 's/\]//g' -e 's/\.\///g' -e 's/ /|/g' | \ tail -n+2 \ > usage_mydir.txt &This gives me the desired output except that it lists all files; i want to filter out files say less than 10MB which will reduce my output file considerably (from over 500 MB to less than 5MB). I am open to any other commands such as find . -type f -size +10M. But I need the owner, size and last modified time of the file.
How to find files greater than a size in linux [duplicate]
socat might work here. On the 2nd PC you could let socat listen for data on /dev/ttyUSB0 and serve it to a tcp port, e.g: socat /dev/ttyUSB0,raw,echo=0 tcp-listen:8888,reuseaddrThen on 1st PC you can connect to 2nd PC with socat and provide the data on a pseudo terminal /dev/ttyVUSB0 for your application: socat PTY,raw,echo=0,link=/dev/ttyVUSB0 tcp:<ip_of_pc2>:8888This isn't tested and socat supports many options, so tweaking may be needed.
I have a device under test (DUT) and I measure its power usage the using a Power Analyzer Datalogger using the data from /dev/ttyUSB0. The problem is that the DUT is now remotely from the workstation I used to gather data with, but in the same network, I need to use a 2nd PC which is directly connected via USB to the Power Analyzer as a sort of USB proxy and ssh to create a kind of symbolic link on the measuring machine of the USB of the "proxy" machine.Given the above diagram how can the 1st PC access /dev/ttyUSB0 of the 2nd PC which is directly connected, in a way that a program reading the stream from the 1st PC will not notice the difference?
How can I set up a "USB proxy" for /dev/ttyUSB0 over the network?
I was able to configure the serial port so echo behaved like screen. Here are my settings: stty -F /dev/ttyUSB0 115200 raw -echo -echoe -echok -echoctl -echokeAnd to echo: echo -e -n 'command_here\r' > /dev/ttyUSB0
I have a small LED matrix controlled by a display driver that accepts serial commands to update the display. I'm successfully controlling it via node with the node serial package, however I'd like to be able to update it with echo so that I can control it earlier in the boot up process with a shell script. To start testing this new method, I set it up with: chmod o+rw /dev/ttyUSB0 stty /dev/ttyUSB0 115200And I'm able to send it commands using screen: screen -F /dev/ttyUSB0 115200However when I try to use: echo -e 'title \r' > /dev/ttyUSB0it doesn't work, and when I monitor the response in another window with cat -v < /dev/ttyUSB0I see that its receiving the message but it seems fragmented and also continuously responding with an error as if I'm sending lots of bad and/or blank commands. How can I mimic the commands sent from screen using echo?
Sending serial commands with echo vs screen session
It's not the commands but the environment in which they run that is the difference. Normally getty is spawned directly from the system service manager (init) – both with systemd where it is a .service, and in the SysV world where it has an inittab entry (and not an init.d script!). This has several differences from being spawned from within another terminal: Primarily, a process started from a terminal inherits it as its "controlling terminal", which is the most important parameter for shell job control. You can see this in ps aux or ps -ef – service processes have no ctty at first, so when getty opens the indicated terminal, that becomes its controlling terminal for job control once the shell is run. But a getty that was started from your xterm will continue to have that xterm pty as its controlling tty despite its input/output now being routed to the serial port – and while getty itself doesn't mind, the shell will also inherit the wrong controlling tty, and that'll make job control impossible. $ ps -C agetty PID TTY TIME CMD 1136 tty1 00:00:00 agetty 14022 pts/22 00:00:00 agetty ^-- should be ttyS0!The controlling terminal defines /dev/tty; it defines which processes job-control signals are sent to; it defines which processes are killed (SIGHUP'd) once the terminal closes. If your shell has inherited a controlling tty that's different from its stdin/out tty, all kinds of weird things may happen. There are ways that a process can detach from its previous terminal, such as calling setsid() – and traditionally /etc/init.d scripts did this to 'daemonize' – but getty does not use them automatically because it doesn't expect to be run this way, so it wasn't programmed in. (There is a setsid tool that could be used to force this to happen, but you shouldn't use it here either; you should do things the right way from start.) You should ideally just systemctl start serial-getty@ttyUSB0 and let getty run in a clean environment. If custom options are needed, it's better to customize that service using systemctl edit [--full] instead of running getty directly. (If systemd is not used, then edit /etc/inittab; it usually has an example included. Run telinit q to reload the inittab.) There are many other, relatively minor differences between processes started from a shell vs through a service manager – stdin/stdout/stderr will start off as being your terminal at first (getty will close and reopen them, but not all services do); environment variables will be inherited from your 'sudo'; the cgroup will be inherited, which might affect your resource limits; from cgroups, the systemd-logind session will be inherited, and the serial login will not be permitted to start its own); your SELinux security context (or AppArmor profile, or SMACK label) will be inherited if that's in use; etc.
I am trying to set up getty to log in over serial (mainly as an experiment). With almost any configuration, the same thing happens. If my default shell is bash, I get this message after I log in: -bash: cannot set terminal process group (15297): Inappropriate ioctl for device -bash: no job control in this shelland then to prove that it doesn't work, I can't use ctrl+C to stop programs: $ sleep 30 ^Cand it doesn't seem to send the signal. These are the configurations I have tried: I have tried both of these commands # copied from raspberry pi: sudo /sbin/agetty --keep-baud 115200,38400,9600 ttyUSB0 vt220 # something else I read somewhere sudo getty -L ttyUSB0 9600 vt100 # (I know I'm mixing and matching a lot of differences but the result is the same)I have tried both screen and picocom as a client. I have tried using a rasberry pi as a server, and two different ubuntu laptops. I have tried two FTDIs, two RS-485 usb adapters, and a built in RS232 on the getty side with a USB RS232 on the client side. I have also tried changing my default shell to sh and dash. I don't get the message, but ctrl+C still doesn't work as expected The funny thing is - when raspberry pi's automatically configure /dev/ttyAMA0, and it uses exactly the getty command that I have put, job control works! And the terminal settings are almost identical. (except for -iutf8 actually) here are the terminal settings with the FTDI connection, and picocom running: $ stty -a -F /dev/ttyUSB0 speed 9600 baud; rows 24; columns 80; line = 0; intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = <undef>; discard = <undef>; min = 1; time = 0; -parenb -parodd -cmspar cs8 hupcl -cstopb cread clocal -crtscts -ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl ixon ixoff -iuclc -ixany -imaxbel -iutf8 opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 isig -icanon -iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke -flusho -extproc $ stty -a -F /dev/ttyUSB1 speed 9600 baud; rows 0; columns 0; line = 0; intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W; lnext = ^V; discard = ^O; min = 1; time = 0; -parenb -parodd -cmspar cs8 hupcl -cstopb cread clocal -crtscts -ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8 -opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 -isig -icanon -iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke -flusho -extprocWhat am I doing wrong? And why does it work with the built in configuration for the built in serial port on the raspberry pi?
job control doesn't work when I try to set up getty over serial
I have the exact same issue with a USB→serial converter. Worked fine on 20.04 (even 21.10), and with 22.04 I see the device appearing for a short time, then 1 or 2 seconds later, disappears. dmesg output: [ 2713.068159] usb 1-2: new full-speed USB device number 32 using xhci_hcd [ 2713.222910] usb 1-2: New USB device found, idVendor=0403, idProduct=6001, bcdDevice= 6.00 [ 2713.222922] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3 [ 2713.222927] usb 1-2: Product: TTL232RG-VREG1V8 [ 2713.222931] usb 1-2: Manufacturer: FTDI [ 2713.222934] usb 1-2: SerialNumber: FT08D7RY [ 2713.228289] ftdi_sio 1-2:1.0: FTDI USB Serial Device converter detected [ 2713.228361] usb 1-2: Detected FT232RL [ 2713.229373] usb 1-2: FTDI USB Serial Device converter now attached to ttyUSB0 [ 2714.563520] usb 1-2: usbfs: interface 0 claimed by ftdi_sio while 'brltty' sets config #1 [ 2714.564784] ftdi_sio ttyUSB0: FTDI USB Serial Device converter now disconnected from ttyUSB0 [ 2714.564845] ftdi_sio 1-2:1.0: device disconnectedThe culprit, if you look into the dmesg output is the 'brltty' daemon. Somehow it is taking over the ftdi driver (I suppose). Looks like a regression based on what I found here from 2011 (https://bugs.launchpad.net/ubuntu/+source/brltty/+bug/874181). Probably needs to be addressed, as braille access is likely key for accessibility features. Anyhow, the fix for me was: sudo apt remove brltty, and Ican use minicom (my serial bridge of choice) again.
If I connect my ESP32 to my Ubuntu ( 22.04 ) by USB it is available in /dev/ttyUSB0. If I run a call - for example sudo ampy --port /dev/ttyUSB0 ls the error message apears Traceback (most recent call last): File "/usr/local/bin/ampy", line 8, in <module> sys.exit(cli()) File "/usr/lib/python3/dist-packages/click/core.py", line 1128, in __call__ return self.main(*args, **kwargs) File "/usr/lib/python3/dist-packages/click/core.py", line 1053, in main rv = self.invoke(ctx) File "/usr/lib/python3/dist-packages/click/core.py", line 1656, in invoke super().invoke(ctx) File "/usr/lib/python3/dist-packages/click/core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/lib/python3/dist-packages/click/core.py", line 754, in invoke return __callback(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/ampy/cli.py", line 99, in cli _board = pyboard.Pyboard(port, baudrate=baud, rawdelay=delay) File "/usr/local/lib/python3.10/dist-packages/ampy/pyboard.py", line 147, in __init__ raise PyboardError('failed to access ' + device) ampy.pyboard.PyboardError: failed to access /dev/ttyUSB0On Ubuntu 20.04 this works very well, without any problem. But since the upgrade, this issue is thrown. Is there something to change on my Ubuntu settings? The User has the following groups : adm dialout cdrom sudo dip plugdev render lpadmin lxd sambashare docker This is the output of ls. I add two comments to describe the workflow: # Plug in the ESP32 michael@michael-Laptop:~$ ls /dev/tty* /dev/tty /dev/tty14 /dev/tty20 /dev/tty27 /dev/tty33 /dev/tty4 /dev/tty46 /dev/tty52 /dev/tty59 /dev/tty8 /dev/ttyS12 /dev/ttyS19 /dev/ttyS25 /dev/ttyS31 /dev/ttyUSB0 /dev/tty0 /dev/tty15 /dev/tty21 /dev/tty28 /dev/tty34 /dev/tty40 /dev/tty47 /dev/tty53 /dev/tty6 /dev/tty9 /dev/ttyS13 /dev/ttyS2 /dev/ttyS26 /dev/ttyS4 /dev/tty1 /dev/tty16 /dev/tty22 /dev/tty29 /dev/tty35 /dev/tty41 /dev/tty48 /dev/tty54 /dev/tty60 /dev/ttyprintk /dev/ttyS14 /dev/ttyS20 /dev/ttyS27 /dev/ttyS5 /dev/tty10 /dev/tty17 /dev/tty23 /dev/tty3 /dev/tty36 /dev/tty42 /dev/tty49 /dev/tty55 /dev/tty61 /dev/ttyS0 /dev/ttyS15 /dev/ttyS21 /dev/ttyS28 /dev/ttyS6 /dev/tty11 /dev/tty18 /dev/tty24 /dev/tty30 /dev/tty37 /dev/tty43 /dev/tty5 /dev/tty56 /dev/tty62 /dev/ttyS1 /dev/ttyS16 /dev/ttyS22 /dev/ttyS29 /dev/ttyS7 /dev/tty12 /dev/tty19 /dev/tty25 /dev/tty31 /dev/tty38 /dev/tty44 /dev/tty50 /dev/tty57 /dev/tty63 /dev/ttyS10 /dev/ttyS17 /dev/ttyS23 /dev/ttyS3 /dev/ttyS8 /dev/tty13 /dev/tty2 /dev/tty26 /dev/tty32 /dev/tty39 /dev/tty45 /dev/tty51 /dev/tty58 /dev/tty7 /dev/ttyS11 /dev/ttyS18 /dev/ttyS24 /dev/ttyS30 /dev/ttyS9michael@michael-Laptop:~$ ls /dev/tty* /dev/tty /dev/tty14 /dev/tty20 /dev/tty27 /dev/tty33 /dev/tty4 /dev/tty46 /dev/tty52 /dev/tty59 /dev/tty8 /dev/ttyS12 /dev/ttyS19 /dev/ttyS25 /dev/ttyS31 /dev/tty0 /dev/tty15 /dev/tty21 /dev/tty28 /dev/tty34 /dev/tty40 /dev/tty47 /dev/tty53 /dev/tty6 /dev/tty9 /dev/ttyS13 /dev/ttyS2 /dev/ttyS26 /dev/ttyS4 /dev/tty1 /dev/tty16 /dev/tty22 /dev/tty29 /dev/tty35 /dev/tty41 /dev/tty48 /dev/tty54 /dev/tty60 /dev/ttyprintk /dev/ttyS14 /dev/ttyS20 /dev/ttyS27 /dev/ttyS5 /dev/tty10 /dev/tty17 /dev/tty23 /dev/tty3 /dev/tty36 /dev/tty42 /dev/tty49 /dev/tty55 /dev/tty61 /dev/ttyS0 /dev/ttyS15 /dev/ttyS21 /dev/ttyS28 /dev/ttyS6 /dev/tty11 /dev/tty18 /dev/tty24 /dev/tty30 /dev/tty37 /dev/tty43 /dev/tty5 /dev/tty56 /dev/tty62 /dev/ttyS1 /dev/ttyS16 /dev/ttyS22 /dev/ttyS29 /dev/ttyS7 /dev/tty12 /dev/tty19 /dev/tty25 /dev/tty31 /dev/tty38 /dev/tty44 /dev/tty50 /dev/tty57 /dev/tty63 /dev/ttyS10 /dev/ttyS17 /dev/ttyS23 /dev/ttyS3 /dev/ttyS8 /dev/tty13 /dev/tty2 /dev/tty26 /dev/tty32 /dev/tty39 /dev/tty45 /dev/tty51 /dev/tty58 /dev/tty7 /dev/ttyS11 /dev/ttyS18 /dev/ttyS24 /dev/ttyS30 /dev/ttyS9# Plugout and plugin the ESP32 michael@michael-Laptop:~$ ls -l /dev/ttyUSB0 crw-rw---- 1 root dialout 188, 0 MΓ€r 19 06:52 /dev/ttyUSB0michael@michael-Laptop:~$ ls -l /dev/ttyUSB0 ls: Zugriff auf '/dev/ttyUSB0' nicht mΓΆglich: Datei oder Verzeichnis nicht gefundenmichael@michael-Laptop:~$ ls /dev/tty* /dev/tty /dev/tty14 /dev/tty20 /dev/tty27 /dev/tty33 /dev/tty4 /dev/tty46 /dev/tty52 /dev/tty59 /dev/tty8 /dev/ttyS12 /dev/ttyS19 /dev/ttyS25 /dev/ttyS31 /dev/tty0 /dev/tty15 /dev/tty21 /dev/tty28 /dev/tty34 /dev/tty40 /dev/tty47 /dev/tty53 /dev/tty6 /dev/tty9 /dev/ttyS13 /dev/ttyS2 /dev/ttyS26 /dev/ttyS4 /dev/tty1 /dev/tty16 /dev/tty22 /dev/tty29 /dev/tty35 /dev/tty41 /dev/tty48 /dev/tty54 /dev/tty60 /dev/ttyprintk /dev/ttyS14 /dev/ttyS20 /dev/ttyS27 /dev/ttyS5 /dev/tty10 /dev/tty17 /dev/tty23 /dev/tty3 /dev/tty36 /dev/tty42 /dev/tty49 /dev/tty55 /dev/tty61 /dev/ttyS0 /dev/ttyS15 /dev/ttyS21 /dev/ttyS28 /dev/ttyS6 /dev/tty11 /dev/tty18 /dev/tty24 /dev/tty30 /dev/tty37 /dev/tty43 /dev/tty5 /dev/tty56 /dev/tty62 /dev/ttyS1 /dev/ttyS16 /dev/ttyS22 /dev/ttyS29 /dev/ttyS7 /dev/tty12 /dev/tty19 /dev/tty25 /dev/tty31 /dev/tty38 /dev/tty44 /dev/tty50 /dev/tty57 /dev/tty63 /dev/ttyS10 /dev/ttyS17 /dev/ttyS23 /dev/ttyS3 /dev/ttyS8 /dev/tty13 /dev/tty2 /dev/tty26 /dev/tty32 /dev/tty39 /dev/tty45 /dev/tty51 /dev/tty58 /dev/tty7 /dev/ttyS11 /dev/ttyS18 /dev/ttyS24 /dev/ttyS30 /dev/ttyS9---- add dmesg output Ok, this is absolute out of my knowledge... @dirkt can you explane what the output say? The following linkes are red: and there are also a lot of red lines with this message: [ 49.700482] nouveau 0000:01:00.0: gr: DATA_ERROR 0000009c [] ch 2 [003fbf0000 systemd-logind[985]] subc 0 class 9197 mthd 0d78 data 00000004 followed by this one [ 49.832345] gnome-shell[1294]: segfault at 5596ea4d51c5 ip 00007f0afb25ceb7 sp 00007ffddb278bb8 error 4 in libgbm.so.1.0.0[7f0afb256000+7000] and last, i expect that this is focused on my ESP32 conection problem, because theres a lot of USB content [ 83.658545] nouveau 0000:01:00.0: bus: MMIO write of 10000000 FAULT at 002a00 [ !ENGINE ] This is the collection of the output: [ 49.700360] nouveau 0000:01:00.0: gr: DATA_ERROR 0000009c [] ch 2 [003fbf0000 systemd-logind[985]] subc 0 class 9197 mthd 0d78 data 00000004 [ 49.700447] nouveau 0000:01:00.0: gr: DATA_ERROR 0000009c [] ch 2 [003fbf0000 systemd-logind[985]] subc 0 class 9197 mthd 0d78 data 00000004 [ 49.700482] nouveau 0000:01:00.0: gr: DATA_ERROR 0000009c [] ch 2 [003fbf0000 systemd-logind[985]] subc 0 class 9197 mthd 0d78 data 00000004 [ 49.832345] gnome-shell[1294]: segfault at 5596ea4d51c5 ip 00007f0afb25ceb7 sp 00007ffddb278bb8 error 4 in libgbm.so.1.0.0[7f0afb256000+7000] [ 49.832384] Code: 18 c3 90 f3 0f 1e fa 48 8b 07 ff a0 c0 00 00 00 0f 1f 00 f3 0f 1e fa 48 8b 07 ff a0 a8 00 00 00 0f 1f 00 f3 0f 1e fa 48 8b 07 <ff> a0 b0 00 00 00 0f 1f 00 f3 0f 1e fa 48 8b 07 ff a0 b8 00 00 00 [ 50.035755] rfkill: input handler enabled [ 52.299029] rfkill: input handler disabled [ 62.559834] systemd-journald[434]: File /var/log/journal/3f503f1656cc4352a889052ae6692375/user-1000.journal corrupted or uncleanly shut down, renaming and replacing. [ 63.052568] rfkill: input handler enabled [ 65.125545] rfkill: input handler disabled [ 65.339576] audit: type=1400 audit(1647699924.695:85): apparmor="DENIED" operation="capable" profile="/snap/snapd/15177/usr/lib/snapd/snap-confine" pid=3840 comm="snap-confine" capability=4 capname="fsetid" [ 67.400897] audit: type=1326 audit(1647699926.753:86): auid=1000 uid=1000 gid=1000 ses=3 subj=? pid=3840 comm="snap-store" exe="/snap/snap-store/558/usr/bin/snap-store" sig=0 arch=c000003e syscall=314 compat=0 ip=0x7f85943b876d code=0x50000 [ 68.076416] audit: type=1400 audit(1647699927.429:87): apparmor="DENIED" operation="connect" profile="snap.snap-store.ubuntu-software" name="/run/user/1000/at-spi/bus" pid=3840 comm="snap-store" requested_mask="wr" denied_mask="wr" fsuid=1000 ouid=1000 [ 69.760939] audit: type=1107 audit(1647699929.112:88): pid=954 uid=103 auid=4294967295 ses=4294967295 subj=? msg='apparmor="DENIED" operation="dbus_method_call" bus="system" path="/org/freedesktop/PolicyKit1/Authority" interface="org.freedesktop.DBus.Properties" member="GetAll" mask="send" name=":1.7" pid=3840 label="snap.snap-store.ubuntu-software" peer_pid=970 peer_label="unconfined" exe="/usr/bin/dbus-daemon" sauid=103 hostname=? addr=? terminal=?' [ 69.760961] audit: type=1420 audit(1647699929.112:89): subj_apparmor=unconfined [ 69.761676] audit: type=1107 audit(1647699929.112:90): pid=954 uid=103 auid=4294967295 ses=4294967295 subj=? msg='apparmor="DENIED" operation="dbus_method_call" bus="system" path="/org/freedesktop/PolicyKit1/Authority" interface="org.freedesktop.PolicyKit1.Authority" member="CheckAuthorization" mask="send" name=":1.7" pid=3840 label="snap.snap-store.ubuntu-software" peer_pid=970 peer_label="unconfined" exe="/usr/bin/dbus-daemon" sauid=103 hostname=? addr=? terminal=?' [ 69.761696] audit: type=1420 audit(1647699929.112:91): subj_apparmor=unconfined [ 69.788634] audit: type=1107 audit(1647699929.140:92): pid=954 uid=103 auid=4294967295 ses=4294967295 subj=? msg='apparmor="DENIED" operation="dbus_method_call" bus="system" path="/org/freedesktop/PolicyKit1/Authority" interface="org.freedesktop.DBus.Properties" member="GetAll" mask="send" name=":1.7" pid=3840 label="snap.snap-store.ubuntu-software" peer_pid=970 peer_label="unconfined" exe="/usr/bin/dbus-daemon" sauid=103 hostname=? addr=? terminal=?' [ 69.788670] audit: type=1420 audit(1647699929.140:93): subj_apparmor=unconfined [ 69.789381] audit: type=1107 audit(1647699929.140:94): pid=954 uid=103 auid=4294967295 ses=4294967295 subj=? msg='apparmor="DENIED" operation="dbus_method_call" bus="system" path="/org/freedesktop/PolicyKit1/Authority" interface="org.freedesktop.PolicyKit1.Authority" member="CheckAuthorization" mask="send" name=":1.7" pid=3840 label="snap.snap-store.ubuntu-software" peer_pid=970 peer_label="unconfined" exe="/usr/bin/dbus-daemon" sauid=103 hostname=? addr=? terminal=?' [ 70.362315] kauditd_printk_skb: 1 callbacks suppressed [ 70.362322] audit: type=1400 audit(1647699929.717:96): apparmor="DENIED" operation="open" profile="snap.snap-store.ubuntu-software" name="/etc/PackageKit/Vendor.conf" pid=3840 comm="snap-store" requested_mask="r" denied_mask="r" fsuid=1000 ouid=0 [ 83.651321] ACPI: \_SB_.PCI0.PEG0.PEGP: failed to evaluate _DSM [ 83.658545] nouveau 0000:01:00.0: bus: MMIO write of 10000000 FAULT at 002a00 [ !ENGINE ] [ 180.681078] usb 2-1.4: new full-speed USB device number 4 using ehci-pci [ 180.828308] usb 2-1.4: New USB device found, idVendor=10c4, idProduct=ea60, bcdDevice= 1.00 [ 180.828315] usb 2-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=3 [ 180.828317] usb 2-1.4: Product: CP2102 USB to UART Bridge Controller [ 180.828319] usb 2-1.4: Manufacturer: Silicon Labs [ 180.828320] usb 2-1.4: SerialNumber: 0001 [ 180.855749] usbcore: registered new interface driver usbserial_generic [ 180.855768] usbserial: USB Serial support registered for generic [ 180.859082] usbcore: registered new interface driver cp210x [ 180.859114] usbserial: USB Serial support registered for cp210x [ 180.859154] cp210x 2-1.4:1.0: cp210x converter detected [ 180.860044] usb 2-1.4: cp210x converter now attached to ttyUSB0 [ 180.914950] input: PC Speaker as /devices/platform/pcspkr/input/input23 [ 181.433918] input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input24 [ 182.932720] usb 2-1.4: usbfs: interface 0 claimed by cp210x while 'brltty' sets config #1 [ 182.933473] cp210x ttyUSB0: cp210x converter now disconnected from ttyUSB0 [ 182.933505] cp210x 2-1.4:1.0: device disconnected [ 249.064792] usb 2-1.4: USB disconnect, device number 4 [ 252.466888] usb 3-2: new full-speed USB device number 2 using xhci_hcd [ 252.665144] usb 3-2: New USB device found, idVendor=10c4, idProduct=ea60, bcdDevice= 1.00 [ 252.665164] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3 [ 252.665170] usb 3-2: Product: CP2102 USB to UART Bridge Controller [ 252.665175] usb 3-2: Manufacturer: Silicon Labs [ 252.665180] usb 3-2: SerialNumber: 0001 [ 252.683233] cp210x 3-2:1.0: cp210x converter detected [ 252.689407] usb 3-2: cp210x converter now attached to ttyUSB0 [ 268.444106] usb 3-2: usbfs: interface 0 claimed by cp210x while 'brltty' sets config #1 [ 268.447566] cp210x ttyUSB0: cp210x converter now disconnected from ttyUSB0 [ 268.447632] cp210x 3-2:1.0: device disconnected [ 355.671608] nouveau 0000:01:00.0: Enabling HDA controller [ 362.191120] ACPI: \_SB_.PCI0.PEG0.PEGP: failed to evaluate _DSM [ 389.497934] usb 3-2: USB disconnect, device number 2 [ 392.335966] usb 3-2: new full-speed USB device number 3 using xhci_hcd [ 392.533200] usb 3-2: New USB device found, idVendor=10c4, idProduct=ea60, bcdDevice= 1.00 [ 392.533210] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3 [ 392.533214] usb 3-2: Product: CP2102 USB to UART Bridge Controller [ 392.533218] usb 3-2: Manufacturer: Silicon Labs [ 392.533221] usb 3-2: SerialNumber: 0001 [ 392.550293] cp210x 3-2:1.0: cp210x converter detected [ 392.556443] usb 3-2: cp210x converter now attached to ttyUSB0 [ 410.282303] usb 3-2: usbfs: interface 0 claimed by cp210x while 'brltty' sets config #1 [ 410.285810] cp210x ttyUSB0: cp210x converter now disconnected from ttyUSB0 [ 410.285877] cp210x 3-2:1.0: device disconnected
/dev/ttyUSB0 is available but after try to call it's gone
Your device isn't being assigned a serial device path because it's not a serial port. From your lsusb output, we see: Bus 001 Device 004: ID 1a86:5512 QinHeng Electronics CH341 in EPP/MEM/I2C mode, EPP/I2C adapterThe key part is in EPP/MEM/I2C mode. The device is not configured as a UART; if it were, we would see: Bus 001 Device 004: ID 1a86:5523 QinHeng Electronics CH341 in serial mode, usb to serial port converterNo amount of driver installation is going to make the device in its current configuration show up as a USB serial port. The issue is entirely in how the device itself is configured. If you have a bare board, you can configure it yourself. According to the data sheet, the selection between UART and SPI/I2C mode is configured via the SCL and SDA pins (see section 5.3, "Function configuration"). If you have a consumer product that's meant to be a UART-to-USB device, I would return it for a replacement.
I have a CH341a Programmer and when I plug it into a usb port everything seems to be working except it doesn't get assigned to a Device Path (eg /dev/ttyUSB0). Does anyone have any clue as to why this might be happening, or how to resolve this issue? Here are some of the things I've done to troubleshoot. lsusb Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 004: ID 1a86:5512 QinHeng Electronics CH341 in EPP/MEM/I2C mode, EPP/I2C adapter Bus 001 Device 003: ID 0e0f:0002 VMware, Inc. Virtual USB Hub Bus 001 Device 002: ID 0e0f:0003 VMware, Inc. Virtual Mouse Bus 001 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hubdmesg [347.965641] usb 1-2.1: new full-speed USB device number 4 using uhci_hcd [348.196659] usb 1-2.1: New USB device found, idVendor=1a86, idProduct=5512 [348.196661] usb 1-2.1: New USB device strings: Mfr=0, Product=2, SerialNumber=0 [348.196662] usb 1-2.1: Product: USB UART-LPTYou can see that the device is being recognized as connected, but no device path assignment. I've connected this thing to 4 different devices and they all behave in the same way with the same output to lsusb and dmesg. This example output is from an Ubuntu VM, but the others were Linux Mint running on a Thinkpad P15s, Zorin running on an old Dell Latitude, and Kali on a Raspi 4. Oh, I've also tried installing drivers from https://github.com/juliagoda/CH341SER and I've uninstalled the BRLTTY software from all test devices (which actually cleared up the issue for my Arduino Nano, but not this device). All updates have been installed and every system is UTD as of the time of this posting. Any and all help is much appreciated. Thanks.
Why isn't my CH341a Device Getting Assigned a Device Path (/dev/ttyUSB0)
I don't think it's supposed to. If I remember correctly, USBasp works with custom control transfers, and e.g. avrdude looks it up from /dev/bus/usb by the vendor and product IDs and ID strings. With avrdude, something like this should work, or complain that it can't find a USB device with the correct IDs: avrdude -P usb -c usbasp -p $UCAlso, since USBasp works with software-implemented USB, it's limited to low-speed operation, which in principle means that it can't work as a serial port:The USB CDC class is intended for modems and other communication devices. [...] CDC requires bulk endpoints which are forbidden for low speed devices by the USB specification. (quote from the V-USB wiki)
I bought an USBASP 2.0 programmer and hooked it up, I cannot see any port created by the programmer. What I expect is USBtty0 in /dev To fix it I have restarted UDEV and tried other UDEV configurations but it doesn't show. uname Linux Puc 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:33:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linuxlsusb Bus 003 Device 092: ID 16c0:05dc Van Ooijen Technische Informatica shared ID for use with libusbdmesg [181622.326920] usb 3-5: new low-speed USB device number 92 using xhci_hcd [181622.460268] usb 3-5: New USB device found, idVendor=16c0, idProduct=05dc [181622.460270] usb 3-5: New USB device strings: Mfr=1, Product=2, SerialNumber=0 [181622.460271] usb 3-5: Product: USBasp [181622.460272] usb 3-5: Manufacturer: www.fischl.deudev rule SUBSYSTEMS=="usb", ENV{DEVTYPE}=="usb_device", ATTRS{idVendor}=="16c0", ATTRS{idProduct}=="05dc", MODE="0666"this device: http://www.fischl.de/usbasp/ [EDIT] Using this command from the arduino/hardware/tools/avr directory, the connection works, just not from within the Arduino IDE. ./bin/avrdude -C etc/avrdude.conf -c usbasp -P usb -p m328p avrdude: warning: cannot set sck period. please check for usbasp firmware update. avrdude: AVR device initialized and ready to accept instructionsReading | ################################################## | 100% 0.00savrdude: Device signature = 0x1e950favrdude: safemode: Fuses OK (H:05, E:DF, L:FF)avrdude done. Thank you.
USBasp not creating ttyUSB0